1.长连接的概念理解
长连接其实就是建立了一次连接 然后中间redis的命令都能一直使用,每次使用都不需要重新建立一个连接,这样可以减少建立redis连接时间。
redis的长连接的生命周期是一个php-fpm进程的时间。再php-fpm这个进程没有关闭之前,这个长连接都是有效的。直观的查看方式就是连续调用两次$redis->connect();和 $redis->pconnect(); 第一个返回的两次的资源id是不一样的,第二个长连接的方式是一样的。
2.长连接的使用
长连接使用其实很简单,直接用pconnect的函数就表示长连接的了。
3.实际使用的代码
这里直接贴代码好了。是我们封装好的一个redis调用的类,这个是继承yii里面的组件的方式。
<?php
namespace extensions\redis;
use yii\base\Component;
class Connection extends Component
{
public $hostname = 'localhost';
public $port = 6379;
public $password;
public $redis;
public function connect()
{
$this->redis = new \Redis();
$this->redis->connect($this->hostname, $this->port);
if ($this->password !== null) {
$this->redis->auth($this->password);
}
}
public function pconnect()
{
$this->redis = new \Redis();
$this->redis->pconnect($this->hostname, $this->port);
if ($this->password !== null) {
$this->redis->auth($this->password);
}
}
public function getRedis($pconnect=false)
{
if($pconnect){
$this->pconnect();
}else{
$this->connect();
}
return $this->redis;
}
public function __call($name, $params = [])
{
switch ($name) {
case 'set':
return $this->redis->set($params[0], $params[1]);
case 'get':
return $this->redis->get($params[0]);
case 'del':
return $this->redis->del($params[0]);
case 'hGet':
return $this->redis->hGet($params[0], $params[1]);
case 'hSet':
return $this->redis->hSet($params[0], $params[1], $params[2]);
case 'hDel':
return $this->redis->hDel($params[0], $params[1]);
case 'hGetAll':
return $this->redis->hGetAll($params[0]);
case 'hMSet':
return $this->redis->hMSet($params[0], $params[1]);
case 'hMGet':
return $this->redis->hMSet($params[0], $params[1]);
case 'lPush':
return $this->redis->lPush($params[0], $params[1]);
case 'rPush':
return $this->redis->rPush($params[0], $params[1]);
case 'lPop':
return $this->redis->lPop($params[0]);
case 'rPop':
return $this->redis->rPop($params[0]);
case 'lLen':
return $this->redis->lLen($params[0]);
case 'lRange':
return $this->redis->lRange($params[0], $params[1], $params[2]);
case 'incr':
return $this->redis->incr($params[0]);
case 'expire':
return $this->redis->expire($params[0],$params[1]);
case 'publish':
return $this->redis->publish($params[0],$params[1]);
}
}
}
本文介绍了Redis长连接的概念,其旨在减少连接建立时间,提高效率。在PHP-FPM进程中,长连接保持有效,直到进程结束。文章还提供了长连接的简单使用方法,以及实际代码示例,展示如何在项目中实现Redis长连接。

847

被折叠的 条评论
为什么被折叠?



