开发一个web项目,总会使用到各种缓存技术,在Zend Framework 2 项目中,就提供了各种缓存服务,如Apc,Filesystem,Memcached等等,这里将介绍使用memcached 的一种简单配置。
配置memcached 时,要确保你的运行环境中是否安装了memcached,如果没有安装则请安装。
本人是在Mac OS X 上,使用ZendServer 作为集成环境,已经安装了memcache 和 memcached。
再者,就是安装成功后,必须开启memcached。本人在测试就因为没有开启memcached ,而输出不了数据。
在Mac OS X 上,使用Terminal(终端),开发memcached 的命令是:
memcached -u memcached -d -m 30 -l 127.0.0.1 -p 11211
我们使用‘cache’配置缓存服务。
1.注册服务到service manager//config/autoload/global.php
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
)
),
2.配置缓存的一些选项。
//config/autoload/global.php
'caches' => array(
'memcached' => array( // //can be called directly via SM in the name of 'memcached'
'adapter' => array(
'name' => 'memcached',
'lifetime' => 7200,
'options' => array(
'servers' => array(
array(
'127.0.0.1',//服务器域名或ip
11211 //服务器tcp端口号,默认值是11211
)
),
'namespace' => 'MYMEMCACHEDNAMESPACE',
'liboptions' => array(
'COMPRESSION' => true,
'binary_protocol' => true,
'no_block' => true,
'connect_timeout' => 100
)
)
),
'plugins' => array(
'exception_handler' => array(
'throw_exceptions' => false
)
)
)
)
$this->getServiceLocator()->get('memcached');
//filling cache value
public function indexAction()
{
$this->getServiceLocator()->get('memcached')->setItem('foo', 'bar');
}
//retrieve cache value
public function retrieveAction()
{
echo $this->getServiceLocator()->get('memcached')->getItem('foo');
}
完成。
参考地址(此地址需要翻墙):http://samsonasik.wordpress.com/2013/10/06/zend-framework-2-using-caches-configuration-to-setting-up-cache-services/