如何将 symfony 应用程序连接到 Azure redis 缓存?

问题描述

symfony 应用程序当前连接到 docker 容器中的 redis 缓存。我在 Azure 上创建了一个新的 Redis 缓存,我正在尝试将它连接到我在另一个 docker 容器中运行的 symfony 应用程序。根据 symfonyredis://[pass@][ip|host|socket[:port]][/db-index].env 文件中存在的连接字符串的格式。就我而言,它是:

REDIS_URL=redis://mypassword@myrediscache.redis.cache.windows.net:6380

应用程序无法连接到 Azure 上的 redis 服务器。该应用程序使用 predis v1.1.1 有一个 Cacheservice.php 服务,其中正在创建 predis 客户端。

$this->client  = new Predis\Client($this->containerInterface->getParameter('REDIS_URL'));

对于现有(容器中的 redis)设置,它工作正常。

REDIS_URL = redis://redis:6379

但是当我将其更改为 REDIS_URL=redis://mypassword@myrediscache.redis.cache.windows.net:6379 时,应用程序无法连接。但是,如果我对连接值进行硬编码,则在创建 predis 客户端的服务中,应用程序能够连接。

以下代码段经过硬编码以连接到端口 6380(启用 SSL)

$this->client = new Predis\Client([
            'scheme' => 'tls','ssl' => ['verify_peer' => true],'host' => 'myrediscache.redis.cache.windows.net','port' => 6380,'password' => 'mypassword'
            ]);

以下代码段经过硬编码以连接到端口 6379(非 SSL)

 $this->client = new Predis\Client([
                'host' => 'myrediscache.redis.cache.windows.net','password' => 'mypassword'
                ]);

请帮我将这些值放在 .env 文件中,而不是对其进行硬编码。顺便说一下,这里还有一些引用 redis 的地方。 snc_redis.yaml 文件:

snc_redis:
    clients:
        default:
            type: predis
            alias: default
            dsn: "%env(REDIS_URL)%"

services.yaml 文件:

parameters:
    REDIS_URL: '%env(resolve:REDIS_URL)%'

我已经为 Azure redis 缓存启用了 6379 端口

解决方法

我可以通过进行以下更改来连接:-

CacheService.php 中(在您的情况下可能会有所不同。predis 客户端的创建和定义位置)

$host = (string)$this->containerInterface->getParameter('REDIS_HOST');
        $port = (int)$this->containerInterface->getParameter('REDIS_PORT');
        $password = (string)$this->containerInterface->getParameter('REDIS_PASSWORD'); 
        $this->client = new Predis\Client([
                'host' => $host,'port' => $port,'password' => $password,'scheme' => 'tls','ssl' => ['verify_peer' => true]
            ]);

services.yaml

中进行以下更改
parameters:
    REDIS_PASSWORD: '%env(resolve:REDIS_PASSWORD)%'
    REDIS_HOST: '%env(resolve:REDIS_HOST)%'
    REDIS_PORT: '%env(resolve:REDIS_PORT)%'

最后但并非最不重要的是,在 .env

REDIS_PASSWORD=mypassword
REDIS_HOST=myrediscache.redis.cache.windows.net
REDIS_PORT=6380

注意:1) 密码不应编码为 utf-8。您应该使用完全相同的密码(您从 azure 门户获得的主密钥)。 2) 另外,如果您要使用端口 6379(非 ssl 端口),请从连接中删除 schemessl 选项。

还要确保从 REDIS_URLservices.yaml 中删除 .env 引用。

希望这也适用于其他人:-)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...