RedisPool.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: huangjianfeng
  5. * Date: 2019-01-10
  6. * Time: 20:41
  7. */
  8. namespace app\command\Org;
  9. class RedisPool
  10. {
  11. private $host;
  12. private $port;
  13. protected $available = true;
  14. public function __construct($host = '127.0.0.1',$port = 6379)
  15. {
  16. $this->pool = new \SplQueue;
  17. $this->host = $host;
  18. $this->port = $port;
  19. }
  20. public function put($redis)
  21. {
  22. $this->pool->push($redis);
  23. }
  24. public function get()
  25. {
  26. //有空闲连接且连接池处于可用状态
  27. if ($this->available && count($this->pool) > 0) {
  28. return $this->pool->pop();
  29. }
  30. //无空闲连接,创建新连接
  31. $redis = new \Swoole\Coroutine\Redis();
  32. // $redis->setOption(\Redis::OPT_SCAN,\Redis::SCAN_RETRY);
  33. $res = $redis->connect($this->host, $this->port);
  34. if ($res == false) {
  35. return false;
  36. } else {
  37. return $redis;
  38. }
  39. }
  40. public function destruct()
  41. {
  42. // 连接池销毁, 置不可用状态, 防止新的客户端进入常驻连接池, 导致服务器无法平滑退出
  43. $this->available = false;
  44. while (!$this->pool->isEmpty()) {
  45. $this->pool->pop();
  46. }
  47. }
  48. }