laravel异步队列的使用

功能实现描述:在做大富翁网页小游戏时候,用户跳转指定步数需要获取相关奖品,例如优惠券,实物奖,此时需要给用户发送系统消息,如果他注册了网站。此时就用到了异步

1.首先在laravel用异步很方便。

PHP artisan make : job  sendprize

创建一个job任务

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SendPrize implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    private $uid;
    private $prize;

    public function __construct($uid = 0, $prize=[])
    {
        //
        $this->uid = $uid;
        $this->prize = $prize;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $prize = $this->prize;
            $uid = $this->uid;
            $prize_id = (int)$prize['origin_id'];
            DB::beginTransaction();
            $prize_info = H5DrawPrizeModel::where([ 'origin_id' => $prize_id, 'flag' => 5 ])->first();
            if ($prize_info->prize_type == 3) {
                $coupon_srv = new CouponService();
               //这里是发送优惠券
                $status = $coupon_srv->getCoupon($uid, (int)$prize_id, true);
                if ($status == 1) {
                    //成功发代金券系统消息
                    $content = [
                        'platform'       => 0,
                        'origin_id'      => 0,
                        'price'          => 0,
                        'uid'            => 0,
                        'tuid'           => $uid,
                        'handler'        => 'coupon',
                        'url'            => 5,
                        'origin_title'   => 'XXXXXX',
                        'origin_content' => 'XXXXXX',
                        ];
                    //这里是发送系统消息
                    $systemMessage = new SystemMessageApi();
                    $aa=$systemMessage->send(4, $content);
                } else {
                    DB::rollback();
                }
            }
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollback();
            Log::error($exception->getMessage());
            return false;
        }

    }
}

2.任务创建好就要去使用了;

 
//控制器里哪里用这个队列就在哪里调用
 
dispatch(new SendPrize($uid, $prize));

3.需要配置env,才有什么队列驱动,我这里配置的是redis

QUEUE_DRIVER=redis

注意

这个你可以使用 PHP artisan queue:work 尝试运行一下自己的队列是否走通

但是每次更改队列的时候记得:PHP artisan config:clear,不然有缓存,队列修改无效

4.接下来就是配置服务器了,这里自行配置

//ok,,,此时你就可以完美使用了,是不是很简单,嘎哈 

猜你喜欢

转载自blog.csdn.net/cfun_goodmorning/article/details/86065058
今日推荐