Redis连接池的使用

2020-05-02  本文已影响0人  骑蚂蚁上高速_jun

1 . 安装

# 安装 redis 连接池
composer require easyswoole/redis-pool --ignore-platform-reqs

2 . 注册 redis 连接池

在 框架 启动事件类 EasySwooleEvent.php 中的 mainServerCreate() 方法中 注册redis连接池
try {
    $redisConfig = new \EasySwoole\Redis\Config\RedisConfig([
         "host"=>"127.0.0.1", // 设置 host
         "port"=>6379,// 设置 端口
         "auth"=>"",// 设置redis登陆密码
         "timeout"=>3, // 选择超时时间
         "reconnectTimes"=>3,// 配置重连时间
         "db"=>0, // 配置使用的数据库
    ]);
    $redisPoolConfig = \EasySwoole\RedisPool\Redis::getInstance()->register('redis',$redisConfig);
    $redisPoolConfig->setMinObjectNum(5); //最小连接 5
    $redisPoolConfig->setMaxObjectNum(20); // 最大连接数 20
    $redisPoolConfig->setGetObjectTimeout(3);
} catch (\Throwable $e) {
    var_dump($e->getMessage());
}
  1. 使用连接池
$redisPool = \EasySwoole\RedisPool\Redis::getInstance()->get('redis');
try {
    $redis = $redisPool->getObj(); // 获取 一个 redis 连接
    $redis->get("name");
    $redisPool->recycleObj($redis); // 归还连接
} catch (\Throwable $e) {
    var_dump($e->getMessage());
}
上一篇 下一篇

猜你喜欢

热点阅读