redis键过期通知

背景概要

  • 背景:为了防止用户长时间不确认收货,需要对订单做24小时后自动确认收货处理
  • 方案:利用Redis的键空间通知和发布订阅机制,结合nohup挂载命令后台守护进程监听,可实现Redis的key过期自动提醒
  • 结果:最终实现订单确认收货超时自动化

其他方案

一开始想到的是cron定时任务,虽然可以勉强满足但不是最佳方案,订单数少的时候很浪费资源

实现

修改redis配置

因为开启键空间通知功能需要消耗一些 CPU , 所以在默认配置下, 该功能处于关闭状态。

参数说明.png
127.0.0.1:6379> config get notify-keyspace-events
1) "notify-keyspace-events"
2) ""
127.0.0.1:6379> config set notify-keyspace-events Ex
OK
127.0.0.1:6379> config get notify-keyspace-events
1) "notify-keyspace-events"
2) "xE"

其实不建议用上面的办法,因为config是危险命令,生产环境禁用,任何客户端都能随便获取配置修改配置,只要客户端连接成功就能随意篡改,只能在测试服使用

Centos修改配置方法还不太一样

修改文件/etc/redis.conf

redis-cli shutdown
redis-server /etc/redis.conf &

vim /etc/redis.conf

此时重新进入 redis-cli 查看 config get notify-keyspace-events 就看到配置生效了

重启redis

/etc/init.d/redis-server restart

redis修改了配置文件,但是一直不生效怎么办,看这篇https://www.cnblogs.com/foundwant/p/5552807.html

键空间通知演示

127.0.0.1:6379> setex name 10 shizhenfeng
OK

再打开一个终端,10秒之后~

127.0.0.1:6379> psubscribe __keyevent@0__:expired
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "__keyevent@0__:expired"
3) (integer) 1
1) "pmessage"
2) "__keyevent@0__:expired"
3) "__keyevent@0__:expired"
4) "name"

结合Laravel artisan实现

创建命令

php artisan make:command OrderExpireListen

代码如下

<?php

namespace App\Console\Commands;

use App\Models\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class OrderExpireListen extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:expire';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '24小时自动确认收货';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $pattern = '__keyevent@0__:expired';
        Redis::subscribe($pattern, function ($channel) {     // 订阅键过期事件
            // 键格式:order_confirm:34
            $keyType = str_before($channel, ':');
            switch ($keyType) {
                case 'order_confirm':
                    $orderId = str_after($channel, ':');
                    $order = Order::find($orderId);
                    if ($order) {
                        $order->status = 5;
                        $order->save();
                        \Log::info("订单 {$order->id} 自动确认收货");
                    }
                    break;
                case 'order_other':
                    // 其他事件,如订单15分钟内未支付自动取消订单
                    break;
                default:
                    break;
            }
        });
    }
}

控制器

    // redis键空间通知
    $key = 'order_confirm:' . $order->id;
    $seconds = 24 * 60 * 60;
    // 值无所谓,关键是key
    Redis::setex($key, $seconds, 1);

报错记录

Error while reading line from the server. [tcp://127.0.0.1:6379]

解决办法:

config/database.php 添加一行

'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
            'read_write_timeout' => 0,  // <----这一条是新加的
        ],

    ],

如何使监听后台始终运行

redis 在执行完订阅操作后,终端进入阻塞状态,需要一直挂在那。且此订阅脚本需要人为在命令行执行,不符合实际需求。

实际上,我们对过期监听回调的需求,是希望它像守护进程一样,在后台运行,当有过期事件的消息时,触发回调函数。 使监听后台始终运行 希望像守护进程一样在后台一样,

Linux中有一个nohup命令。功能就是不挂断地运行命令。 同时nohup把脚本程序的所有输出,都放到当前目录的nohup.out文件中,如果文件不可写,则放到<用户主目录>/nohup.out 文件中。那么有了这个命令以后,不管我们终端窗口是否关闭,都能够让我们的php脚本一直运行。

local环境
nohup php /var/www/wine/artisan order:expire >> /var/www/wine/storage/logs/nohup.log 2>&1 &

dev环境
nohup /usr/bin/php /var/www/html/wine/artisan order:expire >> /var/www/html/wine/storage/logs/nohup.log 2>&1 &

如何证明命令挂上去了

方法一
ps -ef |grep php
控制台输出
root      1216     1  0 01:10 ?        00:00:02 php-fpm: master process (/etc/php/7.1/fpm/php-fpm.conf)
vagrant   1473  1216  0 01:10 ?        00:00:01 php-fpm: pool www
vagrant   1484  1216  0 01:10 ?        00:00:00 php-fpm: pool www
vagrant   1489     1  0 01:10 ?        00:00:01 /usr/bin/hhvm --config /etc/hhvm/php.ini --config /etc/hhvm/server.ini --user vagrant --mode daemon -vPidFile=/var/run/hhvm/pid
vagrant   7909  2842  0 08:24 pts/0    00:00:00 php /var/www/wine/artisan order:expire   <--------看,这里就有了吧
vagrant   7974  2842  0 08:29 pts/0    00:00:00 grep --color=auto php

方法二(只对当前会话有效,关掉窗口就看不到了)
jobs -l
控制台输出
[1]+  7909 Running                 nohup php /var/www/wine/artisan order:expire >> /var/www/wine/storage/logs/nohup.log 2>&1 &

拓展

还能用到哪些需求,比如未支付订单定时关闭

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容