(A)营业场景:
1、当一个营业触发今后须要启动一个定时使命,在指定时候内再去实行一个使命(如自动作废定单,自动完成定单等功用)
2、redis的keyspace notifications 会在key失效后发送一个事宜,监听此事宜的的客户端就能够收到关照
(B)效劳预备:
1、修正reids设置文件(redis.conf)【window体系设置文件为:redis.windows.conf 】
redis默许不会开启keyspace notifications,因为开启后会对cpu有斲丧
备注:E:keyevent事宜,事宜以__keyevent@<db>__为前缀举行宣布;
x:逾期事宜,当某个键逾期并删除时会发生该事宜;
原设置为:
notify-keyspace-events ""
变动 设置以下:
notify-keyspace-events "Ex"
保留设置后,重启Redis效劳,使设置见效
[root@chokingwin etc]# service redis-server restart /usr/local/redis/etc/redis.conf Stopping redis-server: [ OK ] Starting redis-server: [ OK ]
window体系重启redis ,先切换到redis文件目次,然后封闭redis效劳(redis-server --service-stop),再开启(redis-server --service-start)
C)文件代码:
phpredis完成定阅Keyspace notification,可完成自动作废定单,自动完成定单。以下为测试例子
建立4个文件,然后自行修正数据库和redis设置参数
db.class.php
<?phpclass mysql{ private $mysqli; private $result; /** * 数据库衔接 * @param $config 设置数组 */ public function connect() { $config=array( 'host'=>'127.0.0.1', 'username'=>'root', 'password'=>'168168', 'database'=>'test', 'port'=>3306, ); $host = $config['host']; //主机地点 $username = $config['username'];//用户名 $password = $config['password'];//暗码 $database = $config['database'];//数据库 $port = $config['port']; //端口号 $this->mysqli = new mysqli($host, $username, $password, $database, $port); } /** * 数据查询 * @param $table 数据表 * @param null $field 字段 * @param null $where 前提 * @return mixed 查询效果数量 */ public function select($table, $field = null, $where = null) { $sql = "SELECT * FROM `{$table}`"; //echo $sql;exit; if (!empty($field)) { $field = '`' . implode('`,`', $field) . '`'; $sql = str_replace('*', $field, $sql); } if (!empty($where)) { $sql = $sql . ' WHERE ' . $where; } $this->result = $this->mysqli->query($sql); return $this->result; } /** * @return mixed 猎取悉数效果 */ public function fetchAll() { return $this->result->fetch_all(MYSQLI_ASSOC); } /** * 插进去数据 * @param $table 数据表 * @param $data 数据数组 * @return mixed 插进去ID */ public function insert($table, $data) { foreach ($data as $key => $value) { $data[$key] = $this->mysqli->real_escape_string($value); } $keys = '`' . implode('`,`', array_keys($data)) . '`'; $values = '\'' . implode("','", array_values($data)) . '\''; $sql = "INSERT INTO `{$table}`( {$keys} )VALUES( {$values} )"; $this->mysqli->query($sql); return $this->mysqli->insert_id; } /** * 更新数据 * @param $table 数据表 * @param $data 数据数组 * @param $where 过滤前提 * @return mixed 受影响纪录 */ public function update($table, $data, $where) { foreach ($data as $key => $value) { $data[$key] = $this->mysqli->real_escape_string($value); } $sets = array(); foreach ($data as $key => $value) { $kstr = '`' . $key . '`'; $vstr = '\'' . $value . '\''; array_push($sets, $kstr . '=' . $vstr); } $kav = implode(',', $sets); $sql = "UPDATE `{$table}` SET {$kav} WHERE {$where}"; $this->mysqli->query($sql); return $this->mysqli->affected_rows; } /** * 删除数据 * @param $table 数据表 * @param $where 过滤前提 * @return mixed 受影响纪录 */ public function delete($table, $where) { $sql = "DELETE FROM `{$table}` WHERE {$where}"; $this->mysqli->query($sql); return $this->mysqli->affected_rows; } }
index.php
<?php require_once 'Redis2.class.php'; $redis = new \Redis2('127.0.0.1','6379','','15'); $order_sn = 'SN'.time().'T'.rand(10000000,99999999); $use_mysql = 1; //是不是运用数据库,1运用,2不运用 if($use_mysql == 1){ /* * //数据表 * CREATE TABLE `order` ( * `ordersn` varchar(255) NOT NULL DEFAULT '', * `status` varchar(255) NOT NULL DEFAULT '', * `createtime` varchar(255) NOT NULL DEFAULT '', * `id` int(11) unsigned NOT NULL AUTO_INCREMENT, * PRIMARY KEY (`id`) * ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4; */ require_once 'db.class.php'; $mysql = new \mysql(); $mysql->connect(); $data = ['ordersn'=>$order_sn,'status'=>0,'createtime'=>date('Y-m-d H:i:s',time())]; $mysql->insert('order',$data); } $list = [$order_sn,$use_mysql]; $key = implode(':',$list); $redis->setex($key,3,'redis耽误使命'); //3秒后回调 $test_del = false; //测试删除缓存后是不是会有逾期回调。效果:没有回调 if($test_del == true){ //sleep(1); $redis->delete($order_sn); } echo $order_sn; /* * 测试其他key会不会有回调,效果:有回调 * $k = 'test'; * $redis2->set($k,'100'); * $redis2->expire($k,10); * */
psubscribe.php
<?php ini_set('default_socket_timeout', -1); //不超时 require_once 'Redis2.class.php'; $redis_db = '15'; $redis = new \Redis2('127.0.0.1','6379','',$redis_db); // 处置惩罚Redis客户端定阅时刻超时状况 $redis->setOption(); //当key逾期的时刻就看到关照,定阅的key __keyevent@<db>__:expired 这个花样是牢固的,db代表的是数据库的编号,因为定阅开启以后这个库的一切key逾期时候都会被推送过来,所以最好零丁运用一个数据库来举行断绝 $redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), 'keyCallback'); // 回调函数,这里写处置惩罚逻辑 function keyCallback($redis, $pattern, $channel, $msg) { echo PHP_EOL; echo "Pattern: $pattern\n"; echo "Channel: $channel\n"; echo "Payload: $msg\n\n"; $list = explode(':',$msg); $order_sn = isset($list[0])?$list[0]:'0'; $use_mysql = isset($list[1])?$list[1]:'0'; if($use_mysql == 1){ require_once 'db.class.php'; $mysql = new \mysql(); $mysql->connect(); $where = "ordersn = '".$order_sn."'"; $mysql->select('order','',$where); $finds=$mysql->fetchAll(); print_r($finds); if(isset($finds[0]['status']) && $finds[0]['status']==0){ $data = array('status' => 3); $where = " id = ".$finds[0]['id']; $mysql->update('order',$data,$where); } } } //或许 /*$redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), function ($redis, $pattern, $channel, $msg){ echo PHP_EOL; echo "Pattern: $pattern\n"; echo "Channel: $channel\n"; echo "Payload: $msg\n\n"; //................ });*/
Redis2.class.php
<?php class Redis2 { private $redis; public function __construct($host = '127.0.0.1', $port = '6379',$password = '',$db = '15') { $this->redis = new Redis(); $this->redis->connect($host, $port); //衔接Redis $this->redis->auth($password); //暗码考证 $this->redis->select($db); //挑选数据库 } public function setex($key, $time, $val) { return $this->redis->setex($key, $time, $val); } public function set($key, $val) { return $this->redis->set($key, $val); } public function get($key) { return $this->redis->get($key); } public function expire($key = null, $time = 0) { return $this->redis->expire($key, $time); } public function psubscribe($patterns = array(), $callback) { $this->redis->psubscribe($patterns, $callback); } public function setOption() { $this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1); } public function lRange($key,$start,$end) { return $this->redis->lRange($key,$start,$end); } public function lPush($key, $value1, $value2 = null, $valueN = null ){ return $this->redis->lPush($key, $value1, $value2 = null, $valueN = null ); } public function delete($key1, $key2 = null, $key3 = null) { return $this->redis->delete($key1, $key2 = null, $key3 = null); } }
window体系测试要领:先在cmd敕令界面运转psubscribe.php,然后网页翻开index.php。
使监听背景一向运转(定阅)
有个题目 做到这一步,应用 phpredis 扩大,胜利在代码里完成对逾期 Key 的监听,并在 psCallback()里举行回调处置惩罚。开首提出的两个需求已完成。但是这里有个题目:redis 在实行完定阅操纵后,终端进入阻塞状态,须要一向挂在那。且此定阅剧本须要工资在敕令行实行,不符合现实需求。
现实上,我们对逾期监听回调的需求,是愿望它像保卫历程一样,在背景运转,当有逾期事宜的音讯时,触发还调函数。使监听背景一向运转 愿望像保卫历程一样在背景一样,
我是如许完成的。
Linux中有一个nohup敕令。功用就是不挂断地运转敕令。同时nohup把剧本顺序的一切输出,都放到当前目次的nohup.out文件中,假如文件不可写,则放到<用户主目次>/nohup.out 文件中。那末有了这个敕令今后,不论我们终端窗口是不是封闭,都能够让我们的php剧本一向运转。
编写psubscribe.php文件:
<?php #! /usr/bin/env php ini_set('default_socket_timeout', -1); //不超时 require_once 'Redis2.class.php'; $redis_db = '15'; $redis = new \Redis2('127.0.0.1','6379','',$redis_db); // 处置惩罚Redis客户端定阅时刻超时状况 $redis->setOption(); //当key逾期的时刻就看到关照,定阅的key __keyevent@<db>__:expired 这个花样是牢固的,db代表的是数据库的编号,因为定阅开启以后这个库的一切key逾期时候都会被推送过来,所以最好零丁运用一个数据库来举行断绝 $redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), 'keyCallback'); // 回调函数,这里写处置惩罚逻辑 function keyCallback($redis, $pattern, $channel, $msg) { echo PHP_EOL; echo "Pattern: $pattern\n"; echo "Channel: $channel\n"; echo "Payload: $msg\n\n"; $list = explode(':',$msg); $order_sn = isset($list[0])?$list[0]:'0'; $use_mysql = isset($list[1])?$list[1]:'0'; if($use_mysql == 1){ require_once 'db.class.php'; $mysql = new \mysql(); $mysql->connect(); $where = "ordersn = '".$order_sn."'"; $mysql->select('order','',$where); $finds=$mysql->fetchAll(); print_r($finds); if(isset($finds[0]['status']) && $finds[0]['status']==0){ $data = array('status' => 3); $where = " id = ".$finds[0]['id']; $mysql->update('order',$data,$where); } } } //或许 /*$redis->psubscribe(array('__keyevent@'.$redis_db.'__:expired'), function ($redis, $pattern, $channel, $msg){ echo PHP_EOL; echo "Pattern: $pattern\n"; echo "Channel: $channel\n"; echo "Payload: $msg\n\n"; //................ });*/
注重:我们在开首,申明 php 编译器的途径:
#! /usr/bin/env php
这是实行 php 剧本所必需的。
然后,nohup 不挂起实行 psubscribe.php,注重 末端的 &
[root@chokingwin HiGirl]# nohup ./psubscribe.php & [1] 4456 nohup: ignoring input and appending output to `nohup.out'
申明:剧本确切已在 4456 号历程上跑起来。
检察下nohup.out cat 一下 nohuo.out,看下是不是有逾期输出:
[root@chokingwin HiGirl]# cat nohup.out Pattern:__keyevent@0__:expired Channel: __keyevent@0__:expired Payload: name
运转index.php ,3秒后效果如上即胜利
遇到题目:运用敕令行形式开启监控剧本 ,一段时候后报错 :Error while sending QUERY packet. PID=xxx
处置惩罚要领:因为守候音讯行列是一个长衔接,而守候回调前有个数据库衔接,数据库的wait_timeout=28800,所以只需下一条音讯离上一条音讯凌驾8小时,就会涌现这个毛病,把wait_timeout设置成10,而且捕捉非常,发明实在的报错是 MySQL server has gone away ,
所以只需处置惩罚完一切营业逻辑后主动封闭数据库衔接,即数据库衔接主动close掉就能够处置惩罚题目
yii处置惩罚要领以下:
Yii::$app->db->close();
检察历程要领:
ps -aux|grep psubscribe.php a:显现一切顺序 u:以用户为主的花样来显现 x:显现一切顺序,不以终端机来辨别
检察jobs历程ID:[ jobs -l ]敕令
www@iZ232eoxo41Z:~/tinywan $ jobs -l [1]- 1365 Stopped (tty output) sudo nohup psubscribe.php > /dev/null 2>&1 [2]+ 1370 Stopped (tty output) sudo nohup psubscribe.php > /dev/null 2>&1
停止背景运转的历程要领:
kill -9 历程号
清空 nohup.out文件要领:
cat /dev/null > nohup.out
我们在运用nohup的时刻,平常都和&合营运用,但是在现实运用过程当中,很多人背景挂上顺序就如许不论了,实在如许有可能在当前账户非一般退出或许完毕的时刻,敕令照样本身完毕了。
所以在运用nohup敕令背景运转敕令以后,我们须要做以下操纵:
1.先回车,退出nohup的提醒。
2.然后实行exit一般退出当前账户。
3.然后再去链接终端。使得顺序背景一般运转。
我们应当每次都运用exit退出,而不应当每次在nohup实行胜利后直接封闭终端。如许才保证敕令一向在背景运转。
以上就是用PHP+Redis完成耽误使命 完成自动作废定单(细致教程)的细致内容,更多请关注ki4网别的相干文章!