ThinkPHP使用Memcached缓存数据

时间:2023-03-09 09:05:02
ThinkPHP使用Memcached缓存数据

ThinkPHP默认使用文件缓存数据,支持Memcache等其他缓存方式,有两个PHP扩展:Memcache和Memcached,Memcahe官方有说明,主要说一下Memcached。

相对于PHP Memcache,php Memcached是基于原生的c的libmemcached的扩展,更加完善,建议替换为php memcached。

版本3.2.2开始内置了Memcached驱动(ThinkPHP/Library/Think/Cache/Driver/Memcached.class.php),但是文档中并没有说明用法,通过查看源码配置并测试成功。

有个bug至今未修复,就是过期时间为0的问题,理论上应该是永久缓存,但是驱动中未做处理,会马上过期,set方法修改如下

    public function set($name, $value, $expire = null) {
N('cache_write',1);
if(is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'].$name;
if (empty($expire))
$time = 0;
else
$time = time() + $expire;
if($this->handler->set($name, $value, $time)) {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}

在配置文件config.php中添加

//缓存配置
'DATA_CACHE_TYPE' => 'Memcached',
'MEMCACHED_SERVER' => array(
array('127.0.0.1', 11211, 0)
),

驱动中是调用Memcached::addServers(array)可以添加多个缓存服务器

还有一个配置项是 MEMCACHED_LIB,调用的是 Memcached::setOptions(array)

具体选项可参考PHP中文手册