Redis连接池示例

redis-pool组件

可直接安装redis-pool组件实现连接池:

  1. composer require easyswoole/redis-pool

::: warning 通过引入redis-pool组件,直接实现连接池,具体用法可查看redis-pool组件 :::

安装 easyswoole/pool 组件自定义实现:

  1. composer require easyswoole/pool

新增redisPool管理器

新增文件/App/Pool/RedisPool.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Tioncico
  5. * Date: 2019/10/15 0015
  6. * Time: 14:46
  7. */
  8. namespace App\Pool;
  9. use EasySwoole\Pool\Config;
  10. use EasySwoole\Pool\AbstractPool;
  11. use EasySwoole\Redis\Config\RedisConfig;
  12. use EasySwoole\Redis\Redis;
  13. class RedisPool extends AbstractPool
  14. {
  15. protected $redisConfig;
  16. /**
  17. * 重写构造函数,为了传入redis配置
  18. * RedisPool constructor.
  19. * @param Config $conf
  20. * @param RedisConfig $redisConfig
  21. * @throws \EasySwoole\Pool\Exception\Exception
  22. */
  23. public function __construct(Config $conf,RedisConfig $redisConfig)
  24. {
  25. parent::__construct($conf);
  26. $this->redisConfig = $redisConfig;
  27. }
  28. protected function createObject()
  29. {
  30. //根据传入的redis配置进行new 一个redis
  31. $redis = new Redis($this->redisConfig);
  32. return $redis;
  33. }
  34. }

注册到Manager中:

  1. $config = new \EasySwoole\Pool\Config();
  2. $redisConfig1 = new \EasySwoole\Redis\Config\RedisConfig(\EasySwoole\EasySwoole\Config::getInstance()->getConf('REDIS1'));
  3. $redisConfig2 = new \EasySwoole\Redis\Config\RedisConfig(\EasySwoole\EasySwoole\Config::getInstance()->getConf('REDIS2'));
  4. \EasySwoole\Pool\Manager::getInstance()->register(new \App\Pool\RedisPool($config,$redisConfig1),'redis1');
  5. \EasySwoole\Pool\Manager::getInstance()->register(new \App\Pool\RedisPool($config,$redisConfig2),'redis2');

调用(可在控制器中全局调用):

  1. go(function (){
  2. $redis1=\EasySwoole\Pool\Manager::getInstance()->get('redis1')->getObj();
  3. $redis2=\EasySwoole\Pool\Manager::getInstance()->get('redis1')->getObj();
  4. $redis1->set('name','仙士可');
  5. var_dump($redis1->get('name'));
  6. $redis2->set('name','仙士可2号');
  7. var_dump($redis2->get('name'));
  8. //回收对象
  9. \EasySwoole\Pool\Manager::getInstance()->get('redis1')->recycleObj($redis1);
  10. \EasySwoole\Pool\Manager::getInstance()->get('redis2')->recycleObj($redis2);
  11. });

::: warning 详细用法可查看 pool通用连接池 :::

::: warning 本文 redis连接池 基于 pool通用连接池 实现
:::