- 尾部写入
- for ($i=1;$i<=1000;$i++){
- Cache::store('redis')->rpush('list',date("Y-m-d H:i:s")."消息{$i}");
- }
-
- 头部读取消息队列并删除
- $list = Cache::store('redis')->lpop('list');
1、随便建个方法浏览器访问,加入redis消息队列
- public function hello(){
- for ($i=1;$i<=10;$i++){
- Cache::store('redis')->rpush('list1',date("Y-m-d H:i:s")."消息{$i}");
- }
- }
2、队列
tp6创建命令生成文件OrderTask
php think make:command OrderTask
加入命令配置文件config/console.php
- <?php
- // +----------------------------------------------------------------------
- // | 控制台配置
- // +----------------------------------------------------------------------
- return [
- // 指令定义
- 'commands' => [
- //定时任务命令
- 'OrderTask ' => app\command\OrderTask ::class
- ],
- ];
OrderTask .php代码
-
- namespace app\admin\command;
-
- use think\console\Command;
- use think\console\Input;
- use think\console\Output;
- use app\admin\model\Dade;
- use think\facade\Cache;
- use think\facade\Db;
-
- class OrderTask extends Command
- {
- protected function configure()
- {
- $this->setName('ExcelTask');
- }
-
- protected function execute(Input $input, Output $output)
- {
- //php think OrderTask
- $this->start();
- $output->writeln('执行窗口关闭');
- }
-
- /**
- * 启动
- */
- public function start()
- {
- while (1) {
- //执行读取,看效果
- sleep(1);
- $list = Cache::store('redis')->lpop('list1');
- if(!empty($list)){
- try{
- $code = $this->order($list);
- }catch (\Exception $e){
- print_r($e->getMessage());
- echo "\n";
- $code = false;
- }
- if($code == false){
- Cache::store('redis')->rpush('list1',$list."重新加入队列");
- break;
- }
- $data = Date("Y-m-d H:i:s");
- echo $list."----{$data}\n";
- }
- }
- }
-
- public function order($list){
- // 启动事务
- Db::startTrans();
- try {
- $data = [];
- $data['name'] = "大得";
- $data['date'] = $list;
- Dade::create($data);
- // 提交事务
- Db::commit();
- } catch (\Exception $e) {
- print_r($e->getMessage());
- echo "\n";
- // 回滚事务
- Db::rollback();
- return false;
- }
- return true;
- }
-
- }
3、停止后配合Supervisor守护进程再次窗口执行命令
php think OrderTask
为什么要守护进程,因为数据库一段时间连接使用会断开,数据库回收。
开启tp6,有时候也不好使,看情况,我的不好使,可能你的好
// tp6数据库配置是否需要断线重连 'break_reconnect' => true,