这里是用predis写的 , 所以这里需要安装predis composer包
这里哨兵会自动分配读写的
首先在app \pool 文件夹中创建了这两个文件
其中myConnectionPool是连接池 , RedisIn是创建redis连接
MyConnectionPool.php
<?php
namespace App\Pool;
use Hyperf\Contract\ConnectionInterface;
use Hyperf\Pool\Pool;
class MyConnectionPool extends Pool
{
public function createConnection(): ConnectionInterface
{
return new RedisIn();
}
}
RedisIn.php
<?
namespace App\Pool;
use Hyperf\Contract\ConnectionInterface;
use Hyperf\Pool\Connection as BaseConnection;
class RedisIn extends \Predis\Client implements ConnectionInterface
{
use BaseConnection;
public function getClient()
{
$sentinels = [
'tcp://114.128.31.197:26379' // 哨兵地址 , 可以配置多个
];
$options = [
'replication' => 'sentinel',
'service' => 'sentry_redis', // master-name
'parameters' => [
'password' => 'ygyc', // 主机从机的连接密码
'database' => 10, // redis选择库
],
];
$client = new \Predis\Client($sentinels, $options);
return $client;
}
public function reconnect(): bool
{
return true;
// TODO: Implement reconnect() method.
}
public function check(): bool
{
return true;
// TODO: Implement check() method.
}
public function close(): bool
{
return true;
// TODO: Implement close() method.
}
public function release(): void
{
// TODO: Implement release() method.
}
}
使用方法
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Controller;
use Hyperf\Utils\ApplicationContext;
class IndexController extends AbstractController
{
public function index()
{
$user = $this->request->input('user', 'Hyperf');
$method = $this->request->getMethod();
$container = ApplicationContext::getContainer();
$redisPool = $container->get(\App\Pool\MyConnectionPool::class);
$conn = $redisPool->get();
$redis = $conn->getClient();
echo $redis->set('as',1);
$as = $redis->get('as');
$conn->release();
return [
'method' => $method,
'message' => "Hello {$user}.",
'redis' => $as,
];
}
}
这里我不清楚进程池中有多少进程 , 会不会在协程环境有冲突 , 于是我正在改写2.0版本 , 基于hyperf自有的redis连接池进行测试和改动 , 谁让他们这个不好使呢😒