Redis 消息过期回调
可用于:键值过期,进行回调
例:a.php
<?php
require_once 'Redis.php';
$redis2 = new Redis2();
//5秒后过期
$res = $redis2->setex('kkk',5, "It is no pay");
var_dump($res);exit;
b.php 监听回调
<?php
require_once 'Redis.php';
//不超时,解决Redis客户端订阅时候超时情况
ini_set('default_socket_timeout', -1);
$redis = new Redis2();
// 回调函数,这里写处理逻辑
function keyCallback($redis, $pattern, $chan, $msg){
var_dump($pattern);
var_dump($chan);
var_dump($msg);
var_dump(date('Y-M-D H:i:s')); // 这两行留作查看是否执行回调函数
}
$redis->setOption();
//__keyevent@0__:expired 此处的0:代表几号库,* 代表所有库
$redis->psubscribe(array('__keyevent@0__:expired'), 'keyCallback');
Redis公共类文件Redis.php
/**
* Redis
* @author zlj <389843954@qq.com>
*/
class Redis2
{
private $redis;
public function __construct() {
$this->redis = new \Redis();
//连接服务器
$host = '127.0.0.1';
$port = 6379;
$pwd = '123456';
$this->redis->connect($host, $port);
if($pwd){
//连接远程时授权
$this->redis->auth($pwd);
}
}
public function setOption() {
$this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
}
public function psubscribe($patterns = [], $callback){
$this->redis->psubscribe($patterns, $callback);
}
public function setex($key, $time, $val) {
return $this->redis->setex($key, $time, $val);
}