PHP Redis Client and Replica

本文介绍了如何使用 PHP 的 Predis 客户端库配置 Redis 的主从复制环境。通过设置不同的客户端实例分别用于写操作和读操作,可以实现写操作到主服务器,读操作自动负载均衡到多个从服务器的功能。此外,还提供了 composer.json 文件中关于依赖包的具体配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PHP Redis Client and Replica

We can configure the replica connection client like this:
$timeout_parameters = "&timeout=10&read_write_timeout=10";

$parameters = array(
'tcp://' . $redisHostMaster . "?alias=master&$timeout_parameters",
'tcp://' . $redisHostSlave1 . "?alias=slave1&$timeout_parameters",
'tcp://' . $redisHostSlave2 . "?alias=slave2&$timeout_parameters"
);

$this->clientMaster = new Client($parameters, array('replication' => true));

If we create a new Client every time we use it, it will be good. It can send all the writes to master, all the reads to replica. But if we use a single object of that connection, once it connect to master, it will be master forever. That is what I get from the testings.

So finally, my solution change to this, I will keep 2 singleton clients, one for all writes, one for all reads.
$timeout_parameters = "&timeout=10&read_write_timeout=10";

$parameters = array(
'tcp://' . $redisHostMaster . "?alias=master&$timeout_parameters",
'tcp://' . $redisHostSlave1 . "?alias=slave1&$timeout_parameters",
'tcp://' . $redisHostSlave2 . "?alias=slave2&$timeout_parameters"
);

$this->clientMaster = new Client($parameters, array('replication' => true));
$this->clientSlaves = new Client($parameters, array());

And we upgrade the client to v.1.1.1 to support all these. composer.json is as follow:
{
"autoload" : {
"psr-0": {
"JobProducerPHP": "src/"
}
},
"require": {
"predis/predis": "1.1.1",
"aws/aws-sdk-php": "3.0.6",
"katzgrau/klogger": "dev-master",
"pimple/pimple": "3.0",
"solarium/solarium": "^3.6",
"phpFastCache/phpFastCache": "^4.3"
},
"require-dev": {
"php": ">=5.3.0",
"phpunit/phpunit": "~4.5.1",
"phpunit/dbunit": ">=1.2",
"phpunit/php-invoker": "*"
}
}

We need to execute command as follow:
> ./composer.phar update

References:
https://github.com/nrk/predis/tree/v1.1/examples
https://github.com/nrk/predis/blob/v0.7.1/examples/MasterSlaveReplication.php

https://github.com/nrk/predis/issues/21
https://github.com/nrk/predis/wiki/Connection-Parameters

cluster
https://www.zybuluo.com/phper/note/248555
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值