laravel redis 主从配置

关于redis主从服务器配置就略过了,以下基于你已经配置好好,然后在laravel环境下如何使用。

配置

laravel 使用的是 predis 扩展
composer require predis/predis
vi config/database.php

'redis'=>[
   'cluster' => false,
    'default' => [
        "tcp://" . env("REDIS_DEFAULT_HOST") . ":" . env("REDIS_DEFAULT_PORT") . "?database=0&alias=master",//主
        "tcp://" . env("REDIS_DEFAULT_HOST_R") . ":" . env("REDIS_DEFAULT_PORT_R") . "?database=0&alias=slave_1",//从
        "tcp://" . env("REDIS_DEFAULT_HOST_R2") . ":" . env("REDIS_DEFAULT_PORT_R2") . "?database=0&alias=slave_2",//从
    ],
     'test' => [ 
                'host' => '127.0.0.1',
                'port' => 6379,
                'database' => 1,
            ],//队列用到multi命令
             'options' => [
                'replication' => true,
                'connections' =>[
                    'tcp' => '\App\Services\Redis',
                ],
            ],
];

//master slave   vendor/predis/predis/src/Connection/Aggregate/SentinelReplication.php:189
public function add(NodeConnectionInterface $connection)
    {
        $alias = $connection->getParameters()->alias;

        if ($alias === 'master') {
            $this->master = $connection;
        } else {
            $this->slaves[$alias ?: count($this->slaves)] = $connection;
        }

        $this->reset();
    }

vi app/services/redis.php
//参考 https://github.com/nrk/predis/blob/v1.1/examples/debuggable_connection.php
namespace App\Services;

use \Predis\Command\CommandInterface;
use \Predis\Connection\StreamConnection;

class Redis extends StreamConnection
{
    private $tstart = 0;
    private $debugBuffer = [];

    public function connect()
    {
        $this->tstart = microtime(true);

        parent::connect();
    }

    private function storeDebug(CommandInterface $command, $direction)
    {
        $firtsArg = $command->getArguments();
        $timestamp = (microtime(true) - $this->tstart) * 1000;
        $log = [];
        $log['cmd'] = $command->getId();
        $log['key'] = isset($firtsArg) ?  $firtsArg  : ' ';
        $log['server'] = "$direction $this";
        $log['time'] = $timestamp;
        $data = ['server' => trim($log['server']), 'cmd' => $command->getId(), 'key' => $log['key'],'time' => $timestamp, 'msg' => ['host' => explode(':', trim($log['server']))[0], 'port' => explode(':', trim($log['server']))[1]]]];
        openlog('syslog',LOG_PID|LOG_ODELAY,LOG_LOCAL7);
        syslog(LOG_INFO,json_encode($data));
        closelog();
        dump($log);
        $this->debugBuffer[] = $log;
    }

    public function writeRequest(CommandInterface $command)
    {
        parent::writeRequest($command);

//        $this->storeDebug($command, '->');
    }

    public function readResponse(CommandInterface $command)
    {
        $response = parent::readResponse($command);
        $this->storeDebug($command, '');

        return $response;
    }

    public function getDebugBuffer()
    {
        return $this->debugBuffer;
    }

    public static function debug()
    {
        $options = [
            'connections' =>[
                'tcp' => '\App\Services\Redis',
            ],
        ];

        $client = new \Predis\Client(config('database.redis.default'), $options);
        $client->get('redis:test');
        print_r($client->getConnection());
    }
}

注意

看文档 https://github.com/nrk/predis 需要将 replication 设置为true

The basic configuration needed to use the client in replication mode requires one Redis server to be identified as the master (this can be done via connection parameters using the alias parameter set to master) and one or more servers acting as slaves:

clipboard.png

使用

//具体参数含义 vendor/predis/predis/src/Connection/ParametersInterface.php:16
$redis = new \Predis\Client([
                'scheme' => 'tcp',
                'host'   => '127.0.0.1',
                'port'   => 6379,
                'read_write_timeout' => 0,
            ]);
        $redis = \Redis::connection('default');
        $key = 'master:test';
        $redis->set($key, 666);//tail -f /var/log/messages 查看Redis日志可以看到使用的从服务器 REDIS_DEFAULT_HOST_R
        dump($redis->get($key));    //查看Redis日志可以看到使用的主服务器 REDIS_DEFAULT_HOST
               
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Redis 主从配置是一种常见的分布式架构,可以提高 Redis 的可用性和性能。下面是 Redis 主从配置的步骤: 1. 在主服务器上修改配置文件redis.conf,将slaveof选项设置为空,表示该服务器为主服务器。同时,将bind选项设置为主服务器的IP地址,以便从服务器连接主服务器。 2. 在从服务器上修改配置文件redis.conf,将slaveof选项设置为主服务器的IP地址和端口号,表示该服务器为从服务器。同时,将bind选项设置为从服务器的IP地址,以便主服务器连接从服务器。 3. 启动主服务器和从服务器的Redis服务。 4. 在主服务器上执行命令config get *slave*,查看主服务器的slave信息,确认从服务器已经连接到主服务器。 5. 在从服务器上执行命令info replication,查看从服务器的复制信息,确认从服务器已经复制了主服务器的数据。 6. 测试主从配置的可用性和性能。 下面是一个示例,假设主服务器的IP地址为192.168.1.100,从服务器的IP地址为192.168.1.101,端口号都为6379: 1. 在主服务器上修改配置文件redis.conf: ``` # 修改前 slaveof 192.168.1.101 6379 bind 127.0.0.1 # 修改后 slaveof bind 192.168.1.100 ``` 2. 在从服务器上修改配置文件redis.conf: ``` # 修改前 slaveof no one bind 127.0.0.1 # 修改后 slaveof 192.168.1.100 6379 bind 192.168.1.101 ``` 3. 启动主服务器和从服务器的Redis服务: ``` redis-server /path/to/redis.conf ``` 4. 在主服务器上执行命令config get *slave*: ``` 127.0.0.1:6379> config get *slave* 1) "slaveof" 2) "" ``` 5. 在从服务器上执行命令info replication: ``` 127.0.0.1:6379> info replication # Replication role:slave master_host:192.168.1.100 master_port:6379 ... ``` 6. 测试主从配置的可用性和性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值