我在让 Redis 缓存在我的 ZF3 应用程序中工作时遇到问题。
我一直在尝试从各种网站(包括 SO)拼凑出如何做到这一点,但我真的不确定我是否采取了正确的方式。
到目前为止我正在做的是:
在我的 global.php 配置文件中,我添加了:
...
'redis_cache' => [
'adapter' => [
'name' => 'redis',
'options' => [
'server' => [
'host' => '127.0.0.1',
'port' => 6379,
]
]
],
]
...
在我的 Controller 中我有
use Zend\Cache\StorageFactory;
然后在一个方法中我尝试使用
测试缓存$redis = StorageFactory::factory ($this->config['redis_cache']);
if ($redis->hasItem ('mykey'))
{
$value = $redis->getItem('mykey');
}
echo 'value = ' . $value;
这不是获取值。但是,如果我在 $redis 上执行 print_r() ,我可以看到已经创建了 Redis 对象。
最佳答案
如果对其他人有帮助,这是我找到的解决方案。
首先,我需要安装 zend-serializer,我已经安装了 zend-cache。
php composer require zendframework/zend-serializer
然后在/config/autoload/global.php 我添加了
'caches' => [
'RedisCache' => [
'adapter' => [
'name' => Redis::class,
'options' => [
'server' => [
'host' => '127.0.0.1',
'port' => '6379',
],
],
],
'plugins' => [
[
'name' => 'serializer',
'options' => [
],
],
],
],
],
在/config/application.config.php中我添加了
'service_manager' => [
'factories' => [
\Zend\Cache\Storage\Adapter\Redis::class => InvokableFactory::class
]
]
最后,在我的 Controller 工厂中,我像这样设置了依赖注入(inject)
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$cache = $container->get('RedisCache');
return new IndexController($cache);
}
为了在我的 Controller 中使用缓存,我将缓存添加到我的构造函数中
public function __construct($cache)
{
$this->cache = $cache;
}
在一个方法中:
$this->cache->setItem('foo', 'bar');
echo $this->cache->getItem('foo');
关于php - Zend Framework 3 redis 缓存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54311807/