Thinkphp加Redis实现订单超时自动取消功能

一、环境安装:

nginx1.8 + php73 + mysql57 +redis6环境安装略过

    安装thinkphp composer create-project topthink/think tp 缓存管理composer require topthink/think-cacheTP6默认自带里面包含Redis类 安装phpredis扩展:composer require predis/preids

二、环境配置

  1. PHP开启Redis扩展 下载地址: 或者 windows开启,打开php.ini添加 extension=php_redis.dll Linux开启 vim /usr/local/php/etc/php.ini extension = redis.so
  2. Redis设置 linux配置文件名:redis.conf windows位置文件名:redis.windows.conf 打开Redis配置文件,找到notify-keyspace-events ""修改为notify-keyspace-events Ex;
  3. 重启PHP和Redis服务

三、代码部分

配置文件

config/cache.php 如果没有新建一个

return [
    // 默认缓存驱动
    default => env(cache.driver, file),

    // 缓存连接方式配置
    stores => [
        file => [
            // 驱动方式
            type => File,
            // 缓存保存目录
            path => ,
            // 缓存前缀
            prefix => ,
            // 缓存有效期 0表示永久缓存
            expire => 0,
            // 缓存标签前缀
            tag_prefix => tag:,
            // 序列化机制 例如 [serialize, unserialize]
            serialize => [],
        ],
        // 添加Redis配置 
        redis => [
            type => redis,
            host => 127.0.0.1,
            port => 6379,
            password => ,
            select => 0,
            // 全局缓存有效期(0为永久有效)
            expire => 0,
            // 缓存前缀
            prefix => ,
            timeout => 3600 * 24,
        ],
    ],
];

config/console.php 如果没新建一个此文件及代码是为了自定义Command下面有流程,和这个文件先放在这里

return [
    // 指令定义
    commands => [
        GoRedis => appcontrollerGoRedis
    ],
];

自定义一个Command

appcontroller下面新建一个GoRedis.php代码如下

<?php
/**
 *Created by PhoStorm
 *Author:Shen Guoan  13937100809
 *Date:2022/2/22
 *Time:14:47
 */
namespace appcontroller;

use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleOutput;
use thinkfacadeCache;

class GoRedis extends Command
{
          
   
    protected function configure()
    {
          
   
        $this->setName(GoRedis)->setDescription(Here is the GoRedis);
    }

    protected function execute(Input $input, Output $output)
    {
          
   
        $output->writeln(开始监听...);
        Cache::store(redis)->handler()->config(notify-keyspace-events,Ex);
        Cache::store(redis)->handler()->setOption(Redis::OPT_READ_TIMEOUT, -1);
        Cache::store(redis)->handler()->psubscribe(array(__keyevent@0__:expired), appcontrollerGoRedis::key_callback);

    }
    public static function key_callback($redis, $pattern, $channel, $payload){
          
   
        echo "Pattern: $pattern
";
        echo "Channel: $channel
";
        echo "Payload: $payload
";
        /*TODO处理业务逻辑*/
    }

}

使用方法

//假如您的订单为$order
	//开启 1个小时后,任务自动取消
    $data=[操作类型根据您自己需要,$orde[order_id],$order[user_id]];
    //序列化 或 转换成字符串
    //$pusher_data=serialize($pusher_data);
    pusher_data=implode($data,,);//转换成字符串
    Cache::store(redis)->set($data,$data,3600);

开始-》输入-》cmd 输入

php think GoRedis

如图 今天太晚了先写到这里,后面还有点进程守护(Supervisor)

经验分享 程序员 微信小程序 职场和发展