tp5命令行+redis发布订阅实现定时任务原创

原创
小哥 3年前 (2022-11-11) 阅读数 18 #PHP
文章标签 PHP

最近,我遇到了一个要求,谁得到更多的赞扬,谁就会在指定的时间内(可能是几天内)获胜。我今天试过了。redis消息订阅,发现还可以,写下具体流程。

1.安装redis,phpredis扩展

互联网上的大量搜索

2.搜了个redis类,新类:app\common\controller\MyRedis,代码如下:

redis = new Redis();
        $this->redis->config(notify-keyspace-events,Ex);//开启redis key 过期通知(配置文件已修改,但未成功。)
        $this->redis->connect($host, $port);
    }

    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 subscribe($patterns = array(), $callback)
    {
        $this->redis->subscribe($patterns, $callback);
    }

    public function setOption()
    {
        $this->redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
    }

}

请注意我的代码注释中的一句话:

3.使用tp5命令行

在application下的新文件command.php(如果你没有,那就建一个新的吧。),代码:

然后新建 application\index\command\Index.php,代码如下:

setName(hello)
            ->setDescription(Say Hello world);
    }

    protected function execute(Input $input, Output $output)
    {
        $redis = new MyRedis();
        $redis->setOption();
        $redis->psubscribe(array(__keyevent@0__:expired), function ($redis, $pattern, $chan, $msg){
//            echo $msg. ;
//            $teacher = new Teacher();
//            $teacher->name = $msg;
//            $teacher->save();
            var_dump($redis,$pattern,$chan,$msg);
        });

    }

}

建了一个 “hello“司令部,重点是execute()方法,redis的psubscribe监听 “0“这个数据库,有 key "expired"(过期)执行以下回调方法,可在回调方法中使用。curl以编写接口的方式调用,功能逻辑改变也不需要在这里修改命令行上的代码$msg参数是过期的密钥名,我应该在这里存储一项。id。

4.执行

在项目根目录中,首先。php think查看是否已存在“hello“这一命令,

然后执行hello命令

现在“监听”有没有过期日期?key如果是,它将被打印出来:

5.完善

1)使用supervisor将"php think hello"命令加入守护程序命令,并将supervisor设置启动

安装supervisor。。。

在supervisor配置文件supervisord.conf最后,有这样一句话

[include]
files = supervisord.d/*.conf

在相应路径下,创建您自己的新配置文件 hello.conf,其内容如下:

[program:hello]
command=/usr/bin/php /usr/html/php/think hello
process_name=%(program_name)s_%(process_num)02d
;numprocs=5
autostart=true
autorestart=true
startsecs=1 ;当程序重新启动时,它会停留在runing状态的秒数
startretries=10 ;启动失败时的最大重试次数
redirect_stderr=true
user=root
stdout_logfile=/etc/supervisord.d/challenge.log
[supervisord]

[supervisorctl]

注意:command, /usr/bin/php是php运行文件,/usr/html/php/是tp项目根目录,后跟think hello已创建tp命令行,所以这句话的意思是执行 php think hello

stdout_logfile 是日志、echo var_dump如该等输出

此外,每次更改与命令行相关的代码时,都需要重新加载它。supervisor。

2)redis持久化

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除