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



symfony应用程序当前连接到docker容器中的redis缓存。我在Azure上创建了一个新的Redis缓存,并试图将其连接到我的symfony应用程序,该应用程序正在另一个docker容器中运行。根据symfony,redis://[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 PredisClient($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 PredisClient([
'scheme' => 'tls',
'ssl' => ['verify_peer' => true],
'host' => 'myrediscache.redis.cache.windows.net',
'port' => 6380,
'password' => 'mypassword'
]);

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

$this->client = new PredisClient([
'host' => 'myrediscache.redis.cache.windows.net',
'port' => 6380,
'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 PredisClient([
'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选项。

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

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

最新更新