thinkphp6 使用 topthink/think-queue 配置守护进程消息队列

当前演示使用宝塔面板

安装composer require topthink/think-queue

配置config/queue.php

return [
	 //驱动类型,可选择 sync(默认):同步执行,database:数据库驱动,redis:Redis驱动
    'default'     => 'redis', 
    'connections' => [
        'sync'     => [
            'type' => 'sync',
        ],
        'database' => [
            'type'       => 'database',
            'queue'      => 'default',
            'table'      => 'jobs',
            'connection' => null,
        ],
        'redis'    => [
            'type'       => 'redis',
            'queue'      => 'default',
            'host'       => '127.0.0.1',
            'port'       => 6379,
            'password'   => '',
            'select'     => 0,
            'timeout'    => 0,
            'persistent' => false,
        ],
    ],
    'failed'      => [
        'type'  => 'none',
        'table' => 'failed_jobs',
    ],
];

添加消息入队

<?php
namespace app\controller;

use app\BaseController;
use app\job\Test;
use think\facade\Queue;

class Index extends BaseController
{
    public function work()
    {
        // 参数
        $data = [
            'id' => 1,
            'username' => 'zhagnsan',
            'time' => time(),
            'type' => 1
        ];
        $name = 'testQueue';
        $queue = Queue::push(Test::class, $data, $name);
        if($queue != false){
            echo '加入队列成功';
        }else{
            echo '加入队列失败';
        }
    }
}

创建job/Test消耗队列

<?php
namespace app\job;

use think\facade\Log;
use think\queue\Job;

class Test
{
    public function fire(Job $job, $data)
    {
        $isDoJob = $this->doJob($data);
        if($isDoJob){
            $job->delete();
        }else{
            $attempts = $job->attempts();
            if($attempts < 5){
                $job->release(2);
            }
        }
    }

    public function failed($data)
    {
        Log::error('消息队列达到最大重复执行次数后失败');
    }

    public function doJob($data)
    {
        if($data['type'] == 1){
            echo '消息队列执行成功';
            Log::info('执行成功');
            return true;
        }else{
            echo '消息队列执行失败';
            Log::info('执行失败');
            return false;
        }
    }
}

命令调用
php think queue:work --queue testQueue

效果图
在这里插入图片描述

宝塔安装Supervisor
在这里插入图片描述
安装成功后添加守护进程
在这里插入图片描述
启动命令直接使用php think queue:work --queue testQueue,其他根据自己项目情况填写

报错:The Process class relies on proc_open, which is not available on your PHP installation
解决办法:是因为禁用了proc_open函数导致的报错,在php.ini中删掉这个函数重启PHP即可

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值