Kohana的Cache

标签 : , ,

Kohana里有个Cache Library,我今天就测试了一下。

首先要配置,将system/config下的cache.php复制到application/config下,打开cache.php文件,我们看一下内容

1
2
3
4
5
6
7
$config['default'] = array
(
    'driver'   => 'file',
    'params'   => APPPATH.'cache',
    'lifetime' => 1800,
    'requests' => 1000
);

这是一个默认配置,’driver’为驱动的缓存方式,Kohana支持6种不同的驱动,分别是File、SQlite、Memcache、APC、Eaccelerator、Xcache,配置文件默认使用的file,其原理是,写缓存时把对象序列化写入文件,读缓存时从文件读出文本反序列化,所以在文件方式下,缓存是基于I/O的,在文件多而且大的时候,性能会有下降, ‘params’是驱动参数,在file驱动模式下,就是cache文件路径,’lifetime’是cache的生命周期,单位为秒,超过这个时间,内容将被清除(设置为0代表不自动清除),’requests’为在达到请求数量之前自动垃圾回收。

在应用中,可能需要不止一个缓存,所以可以配置多个缓存,增加$config数组即可,还有在file方式下可以为每个缓存设置单独文件路径,但前提是文件路径要存在,例如我们增加一个

1
2
3
4
5
6
7
$config['my'] = array
(
    'driver'   => 'file',
    'params'   => APPPATH.'cache/my',
    'lifetime' => 1800,
    'requests' => 1000
);

接下来我们在Controller里调用cache

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Mycache_Controller extends Controller {
 
    public function index() {
        $mychache = Cache::instance("my");
        $mychache->set("name","laoer");
        echo "OK";   
    }
 
    public function name() {
        $mychache= Cache::instance("my");
        $name = $mychache->get("name");
        echo $name;
    }   
}

Cache::instance(“my”)实例化配置里$config['my']的cache,如果用Cache::instance()就是实例化配置里$config['default']的cache,在浏览器里执行,已经可以存取了,在application/cache/my/文件下可以看到一个名为”name~~0″的文件,里面就是序列化的数据。

文件cache还是有一定的局限性,现在越来越的网站开始使用Memcached所谓缓存的解决方案,Kohana的缓存驱动里,有Memcached的支持,但它的文档却没有给出Memcached的配置例子,看来要自己摸索一下。

将system/config下的cache_memcache.php复制到application/config下,cache_memcache.php的内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * @package  Cache:Memcache
 *
 * memcache server configuration.
 */
$config['servers'] = array
(
	array
	(
		'host' => '127.0.0.1',
		'port' => 11211,
		'persistent' => FALSE,
	)
);
 
/**
 * Enable cache data compression.
 */
$config['compression'] = FALSE;

根据你自己的情况修改Memcached的服务地址和端口,在application/config/cache.php里再加一段

1
2
3
4
5
6
7
$config['mem'] = array
(
	'driver'   => 'memcache',
	'params'   => '',
	'lifetime' => 1800,
	'requests' => 1000
);

在Controller里把Cache::instance(“my”)改为Cache::instance(“mem”),运行看看结果,已经可以从Memcahced里存取了。

Kohana的Memcached驱动还是有些缺陷,现在只能使用一组Memcached,即$config['servers']这个参数,我觉得Memcacahed组也应该是多个,因为从业务角度会根据功能对cache做划分,我大概看了一下system/libraries/drivers/Cache/Memcache.php文件,应该是可以改造的,还有一点,编译PHP的时候要安装Memcached的支持。

Comments:

发表评论

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word