php - Zend Framework 3 redis 缓存问题

标签 php redis zend-framework3

我在让 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/

相关文章:

php - 仅生成具有约束的有效配置

php - 在数据源中找不到 Cake PHP 表

redis - 获取具有给定前缀的所有排序集的大小

php - 我需要解决上传文件问题的帮助和想法,并在后台 Laravel 或 NodeJs 中执行一些任务

php - 在没有 serviceLocator->get() 方式的情况下,ZF2 中新的依赖注入(inject)方式是否更加低效?

mysql - 学说 - 数据库表示

php - 如何修复 'ERROR 2002 (HY000): Can' t 通过套接字 '/var/run/mysqld/mysqld.sock' (2 "No such file or directory") 连接到本地 MySQL 服务器'

php - 如何使用mysql检索最后插入的id?

rspec - 当在一个 RSpec 套件中调用多个 with_api() 测试时,Goliath 会破坏 em-synchrony/em-hiredis

javascript - 将 React 添加到大型 PHP 项目 (ZF3)