使用PHP+Redis实现延迟任务,实现自动取消订单功能
Redis  /  管理员 发布于 5年前   372
简单定时任务解决方案:使用redis的keyspace notifications(键失效后通知事件) 需要注意此功能是在redis 2.8版本以后推出的,因此你服务器上的reids最少要是2.8版本以上; (A)业务场景: 1、当一个业务触发以后需要启动一个定时任务,在指定时间内再去执行一个任务(如自动取消订单,自动完成订单等功能) 2、redis的keyspace notifications 会在key失效后发送一个事件,监听此事件的的客户端就可以收到通知 (B)服务准备: 1、修改reids配置文件(redis.conf)【window系统配置文件为:redis.windows.conf 】 redis默认不会开启keyspace notifications,因为开启后会对cpu有消耗 备注:E:keyevent事件,事件以__keyevent@ x:过期事件,当某个键过期并删除时会产生该事件; 原配置为: 更改 配置如下: 保存配置后,重启Redis服务,使配置生效 window系统重启redis ,先切换到redis文件目录,然后关闭redis服务(redis-server --service-stop),再开启(redis-server --service-start) C)文件代码: phpredis实现订阅Keyspace notification,可实现自动取消订单,自动完成订单。以下为测试例子 创建4个文件,然后自行修改数据库和redis配置参数 db.class.php index.php psubscribe.php Redis2.class.php window系统测试方法:先在cmd命令界面运行psubscribe.php,然后网页打开index.php。 使监听后台始终运行(订阅) 有个问题 做到这一步,利用 phpredis 扩展,成功在代码里实现对过期 Key 的监听,并在 psCallback()里进行回调处理。开头提出的两个需求已经实现。可是这里有个问题:redis 在执行完订阅操作后,终端进入阻塞状态,需要一直挂在那。且此订阅脚本需要人为在命令行执行,不符合实际需求。 实际上,我们对过期监听回调的需求,是希望它像守护进程一样,在后台运行,当有过期事件的消息时,触发回调函数。使监听后台始终运行 希望像守护进程一样在后台一样, 我是这样实现的。 Linux中有一个nohup命令。功能就是不挂断地运行命令。同时nohup把脚本程序的所有输出,都放到当前目录的nohup.out文件中,如果文件不可写,则放到<用户主目录>/nohup.out 文件中。那么有了这个命令以后,不管我们终端窗口是否关闭,都能够让我们的php脚本一直运行。 编写psubscribe.php文件: 注意:我们在开头,申明 php 编译器的路径: 这是执行 php 脚本所必须的。 然后,nohup 不挂起执行 psubscribe.php,注意 末尾的 & 说明:脚本确实已经在 4456 号进程上跑起来。 查看下nohup.out cat 一下 nohuo.out,看下是否有过期输出: 运行index.php ,3秒后效果如上即成功 遇到问题:使用命令行模式开启监控脚本 ,一段时间后报错 :Error while sending QUERY packet. PID=xxx 解决方法:由于等待消息队列是一个长连接,而等待回调前有个数据库连接,数据库的wait_timeout=28800,所以只要下一条消息离上一条消息超过8小时,就会出现这个错误,把wait_timeout设置成10,并且捕获异常,发现真实的报错是 MySQL server has gone away , yii解决方法如下: 查看进程方法: 查看jobs进程ID:[ jobs -l ]命令 终止后台运行的进程方法: 清空 nohup.out文件方法: 我们在使用nohup的时候,一般都和&配合使用,但是在实际使用过程中,很多人后台挂上程序就这样不管了,其实这样有可能在当前账户非正常退出或者结束的时候,命令还是自己结束了。 所以在使用nohup命令后台运行命令之后,我们需要做以下操作: 1.先回车,退出nohup的提示。 2.然后执行exit正常退出当前账户。 我们应该每次都使用exit退出,而不应该每次在nohup执行成功后直接关闭终端。这样才能保证命令一直在后台运行。 总结 以上所述是小编给大家介绍的使用PHP+Redis实现延迟任务,实现自动取消订单功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!notify-keyspace-events ""
notify-keyspace-events "Ex"
[root@chokingwin etc]#service redis-server restart /usr/local/redis/etc/redis.conf Stopping redis-server: [ OK ] Starting redis-server: [ OK ]
'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; }}
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); **/
setOption();//当key过期的时候就看到通知,订阅的key __keyevent@
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); }}
setOption();//当key过期的时候就看到通知,订阅的key __keyevent@
#! /usr/bin/env php
[root@chokingwin HiGirl]# nohup ./psubscribe.php & [1] 4456 nohup: ignoring input and appending output to `nohup.out'
[root@chokingwin HiGirl]# cat nohup.out Pattern:__keyevent@0__:expired Channel: __keyevent@0__:expired Payload: name
所以只要处理完所有业务逻辑后主动关闭数据库连接,即数据库连接主动close掉就可以解决问题Yii::$app->db->close();
ps -aux|grep psubscribe.phpa:显示所有程序u:以用户为主的格式来显示x:显示所有程序,不以终端机来区分
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 进程号
cat /dev/null > nohup.out
3.然后再去链接终端。使得程序后台正常运行。
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!您可能感兴趣的文章:
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号