ThinkPHP3.2.3 Memcache缓存使用概述
本内容详细解析了ThinkPHP 3.2.3版本中Memcache缓存的具体应用技巧,旨在为开发者提供实用的参考方案。
在了解了Linux环境下Memcached服务端与客户端的安装流程后,接下来重点归纳在ThinkPHP 3.2.3框架内如何高效使用Memcache。
第一种实现路径是基于原生Memcache扩展进行编码。
public function test1() {
$mc = new \Memcache(); //创建Memcache对象
$mc->connect("127.0.0.1", 11211); //连接Memcached服务器
$mc->set('test1','hello world',0,10); //存储数据
echo $mc->get('test'); //获取数据
$mc->delete('test'); //删除数据
$mc->flush(); //强制刷新全部缓存,即清空Memcached服务器
$mc->close(); //断开与Memcached服务器的连接
}
第二种路径是直接调用框架内部已封装好的Memcache缓存驱动类。
public function test2() {
$mc = new \Think\Cache\Driver\Memcache(); //实例化Memcache驱动
$mc->set('test2','hello world',60); //写入缓存
echo $mc->get('test2'); //读取缓存
$mc->rm('test2'); //删除指定缓存
$mc->clear(); //清空全部缓存
}
第三种路径是利用ThinkPHP提供的S方法进行操作。
①直接使用S方法接口
public function test3() {
//缓存初始化
S(array(
'type'=>'memcache', //缓存类型
'host'=>'127.0.0.1', //Memcache服务器地址
'port'=>'11211', //Memcache端口号
'prefix'=>'think', //缓存标识前缀
'expire'=>10,) //缓存有效期(时间为秒)
);
//设置缓存
S('test3','hello world'); //可以改变缓存时间:S('test3','hello world',60);
//读取缓存
echo S('test3');
//删除缓存
S('test3',null);
}
②采用对象化方式管理缓存数据
public function test4() {
$cache = S(array('type'=>'memcache','prefix'=>'think','expire'=>10)); //缓存初始化
$cache->test4 = 'hello world'; //设置缓存
echo $cache->test4; //获取缓存
unset($cache->test4); //删除缓存
}
根据官方文档说明,S方法在初始化时若未指定type参数,系统将自动读取配置项DATA_CACHE_TYPE作为默认缓存类型;若未指定prefix参数,则读取DATA_CACHE_PREFIX作为标识前缀;若未指定expire参数,则读取DATA_CACHE_TIME作为默认有效期。
在config.php配置文件中,针对Memcache缓存的相关配置如下所示:
'DATA_CACHE_TYPE' => 'Memcache', //数据缓存类型
'DATA_CACHE_PREFIX' => '', //缓存前缀
'DATA_CACHE_TIME' => 10, //数据缓存有效期 0表示永久缓存
'DATA_CACHE_COMPRESS' => false, //数据缓存是否压缩缓存
完成上述配置后,后续调用S方法时无需再次进行显式初始化。
public function test5() {
//设置缓存
S('test5','hello world');
//读取缓存
echo S('test5');
//删除缓存
S('test5',null);
}
期望上述内容能对基于ThinkPHP框架进行PHP程序开发的读者提供有益帮助。