107.1 laravel使用队列的时候会遇到的问题 一些启动命令

laravel队列问题

ps -fe | grep ‘artisan queue’ |grep -v ‘grep’ | wc -l

ps -fe | grep ‘artisan queue’ |grep -v ‘grep’

grep -v grep 代表在查询的最终结果中去掉grep命令本身
wc -l 标示统计查询到的结果数量

在使用队列的时候,
使用

$this->release(15)

指的是
*将任务释放回队列。
*接受以秒为单位指定的延迟。

上面的代码就是延迟了15秒。

出现死锁情况的方案,可能是排它锁的原因,解决方案
https://learnku.com/laravel/t/46331

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class MyJob implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    public function handle()
    {
        // 处理队列任务
    }

    public function delete()
    {
        // 重写 delete 方法,执行自定义的删除逻辑
    }
}

添加缓存锁的逻辑代码

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class MyJob implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    public function handle()
    {
        $jobId = $this->job->getJobId();
        $cacheKey = "job_lock_{$jobId}";
        
        // 判断缓存中是否存在该任务的锁
        if (Cache::has($cacheKey)) {
            // 如果存在锁,说明任务正在被处理,直接退出
            return;
        }
        
        // 在缓存中设置该任务的锁,有效期为 60 秒
        Cache::put($cacheKey, true, 60);
        
        try {
            // 处理队列任务
        } finally {
            // 在任务执行完成后,删除该任务的锁
            Cache::forget($cacheKey);
        }
    }
}

共通类的使用方法

use Illuminate\Cache\CacheManager;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class BaseJob implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $cache;

    public function __construct(CacheManager $cache)
    {
        $this->cache = $cache;
    }

    public function handle()
    {
        $jobId = $this->job->getJobId();
        $cacheKey = "job_lock_{$jobId}";
        
        // 判断缓存中是否存在该任务的锁
        if ($this->cache->has($cacheKey)) {
            // 如果存在锁,说明任务正在被处理,直接退出
            return;
        }
        
        // 在缓存中设置该任务的锁,有效期为 60$this->cache->put($cacheKey, true, 60);
        
        try {
            // 处理队列任务
            $this->handleJob();
        } finally {
            // 在任务执行完成后,删除该任务的锁
            $this->cache->forget($cacheKey);
        }
    }

    protected function handleJob()
    {
        // 子类继承该方法来实现具体的任务逻辑
    }
}

参考资料:
队列的laravel 文档

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值