hyperf redis-cluster连接

355 阅读1分钟

 这里我之前是使用的redis-sentinel哨兵 , 但是总有redis无法连接的情况发生 , 于是从 1主3从3哨兵直接上cluster集群 , 3主3从

这里有一个注意事项 , 在使用redis-cli的时候需要加上-c 参数 , 否则会报错

配置很简单 , 随便在网上一搜一大堆 , 但是一旦出问题 , 网上有效的解决方案会很少 , 官方文档也不太容易懂 , 很多网上的帖子都是复制粘贴的和想要的结果根本不搭边😒

hyperf关于这里的配置还是很容易的

首先在config\autoload\redis.php 文件中查看一下是否存在关于redis-cluster的配置项

如果没有可以在vendor\hyperf\redis\publish 文件夹下复制一份 , 因为我这里是远程连接服务器开发 , 所以就没使用命令行publish出来, 哈哈

这里的seeds选项是各个redis节点, 我这里是所有节点都写了 ,但是我测试只写一个节点也是好使的

enable选项一定要开启 , 在env下添加一下  REDIS_CLUSTER_ENABLE 就行了

然后 , 这里就可以使用controller试一下好不好使了

使用的时候需要注意 , 获取redis实例不应该是 \Redis , 而是 Hyperf\Redis\Redis  , 需要使用container容器获取实例

下面我写了一个使用phpredis扩展关于cluster的demo

<?php


/**
 *
 *
 * @authors Msy
 * @Created-Time: 2022/11/21 17:28
 */
class RedisClusterHandler
{
    public $connection;
    public function connect()
    {
        $redis = new \RedisCluster(null , [
            '39.206.54.171:6380',
            '114.126.31.197:6380',
            '39.206.54.171:6381',
            '114.126.31.197:6381',
            '39.206.54.171:6382',
            '114.126.31.197:6382'
        ] ,0.0,0.0,false ,'ygycachwk');
        $this->connection = $redis;
        return $redis;
    }

    public function __call($name, $arguments)
    {
        try {
            $result = $this->connection->{$name}(...$arguments);
        } catch (\Throwable $exception) {
            $result = $this->retry($name, $arguments, $exception);
        }
        return $result;
    }

    protected function retry($name, $arguments, \Throwable $exception)
    {
        try {
            $this->connect();
            $result = $this->connection->{$name}(...$arguments);
        } catch (\Throwable $exception) {
            $this->lastUseTime = 0.0;
            throw $exception;
        }
        return $result;
    }
}




$redisC = new RedisClusterHandler();
$redis = $redisC->connect();
$key = $redis->keys('*');
var_dump($key);