redis長連線的原理和示例
阿新 • • 發佈:2018-12-25
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]);
}
}
}