ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
~~~ <?php /** * Created by PhpStorm. * User: Administrator * Date: 2020/12/29 * Time: 14:55 */ namespace lib; class RedisPool{ protected $available = true; public $pool; protected $redis_host='127.0.0.1'; protected $redis_port=6379; protected $redis_auth=''; public function __construct(){ //pop()函数移除栈顶元素 //push() 在末尾加入一个元素 $this->pool = new SplQueue; } public function get() { //有空闲连接且连接池处于可用状态 if ($this->available && count($this->pool) > 0) { $redis = $this->pool->pop(); } else { if(count($this->pool) >= 1000){ return false; } //无空闲连接,创建新连接 $redis = new Redis(); $redis->connect($this->redis_host, $this->redis_port); if ($this->redis_auth) { $redis->auth($this->redis_auth); } } return $redis; } public function put($redis){ $this->pool->push($redis); } public function destruct() { // 连接池销毁, 置不可用状态, 防止新的客户端进入常驻连接池, 导致服务器无法平滑退出 $this->available = false; while (!$this->pool->isEmpty()) { $this->pool->pop(); } } } ~~~