Laravel 7使用swoole+redis每秒處理任務

charliecen發表於2020-09-08

安裝配置點選這裡

redisphpredis 安裝完成後,在配置檔案.env中配置QUEUE_CONNECTION=redis

建立定時任務類

namespace App\Jobs;

use App\Entities\Cron;
use Hhxsv5\LaravelS\Swoole\Timer\CronJob;
use Illuminate\Support\Facades\Log;
use Swoole\Coroutine;

class TestCron extends CronJob
{
    public function run()
    {
        // Swoole>=2.1 run()方法已自動建立了協程。
        Coroutine::sleep(1);
        // 查詢資料庫
        $lists = Cron::where([
            ['exe_time', '<=', time()],
            ['status', '=', 2],
            ['queue_status', '=', 1]
        ])->get();
        // 有資料放入佇列中
        if(count($lists) > 0) {
            // 放入佇列中
            foreach($lists as $k => $v) {
                TestCronJob::dispatch($v)->onConnection('redis')->onQueue('CronJobQueue');
                // 修改佇列狀態為佇列中
                Cron::where(['id' => $v->id])->update(['queue_status' => 2]);
                Log::info(__METHOD__, Cron::find($v->id)->toArray());
            }
        }
    }
}

建立一個佇列類

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TestCronJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    // 佇列資料
    protected $param;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($param)
    {
        $this->param = $param;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 判斷請求方式,2 為get請求
        if ($this->param->type == 2) {
            // todo 業務邏輯
        }
    }
}

配置timer

// 在"config/laravels.php"註冊定時任務類
[
    // ...
    'timer'          => [
        'enable' => env('LARAVELS_TIMER', true), // 啟用Timer
        'jobs'   => [ // 註冊的定時任務類列表
            // 啟用LaravelScheduleJob來執行`php artisan schedule:run`,每分鐘一次,替代Linux Crontab
            // \Hhxsv5\LaravelS\Illuminate\LaravelScheduleJob::class,
            // 兩種配置引數的方式:
            // [\App\Jobs\Timer\TestCronJob::class, [1000, true]], // 註冊時傳入引數
            \App\Jobs\TestCron::class, // 過載對應的方法來返回引數
        ],
        'max_wait_time' => 5, // Reload時最大等待時間
        // 開啟全域性定時器開關:當多例項部署時,確保只有一個例項執行定時任務,此功能依賴 Redis,具體請看 https://learnku.com/docs/laravel/7.x/redis
        'global_lock'     => false,
        'global_lock_key' => config('app.name', 'Laravel'),
    ],
    // ...
];

測試

  1. 首先啟動laravals
$ php bin/laravels start
 _                               _  _____ 
| |                             | |/ ____|
| |     __ _ _ __ __ ___   _____| | (___  
| |    / _` | '__/ _` \ \ / / _ \ |\___ \ 
| |___| (_| | | | (_| |\ V /  __/ |____) |
|______\__,_|_|  \__,_| \_/ \___|_|_____/ 

Speed up your Laravel/Lumen
>>> Components
+---------------------------+---------+
| Component                 | Version |
+---------------------------+---------+
| PHP                       | 7.4.9   |
| Swoole                    | 4.5.3   |
| LaravelS                  | 3.7.8   |
| Laravel Framework [local] | 7.27.0  |
+---------------------------+---------+
>>> Protocols
+-----------+--------+-------------------+----------------+
| Protocol  | Status | Handler           | Listen At      |
+-----------+--------+-------------------+----------------+
| Main HTTP | On     | Laravel Framework | 127.0.0.1:5200 |
+-----------+--------+-------------------+----------------+
>>> Feedback: https://github.com/hhxsv5/laravel-s
[2020-09-07 16:17:59] [TRACE] Swoole is running, press Ctrl+C to quit.
  1. 啟動佇列
$ php artisan queue:work redis  --queue=CronJobQueue
[2020-09-07 16:18:07][wxEp2oOyhnyMBGiCl309MLS7szGnz5gs] Processing: App\Jobs\TestCronJob
[2020-09-07 16:18:07][wxEp2oOyhnyMBGiCl309MLS7szGnz5gs] Processed:  App\Jobs\TestCronJob
  1. 修改資料庫資料
  2. 檢視日誌
[2020-09-07 16:18:25] local.INFO: App\Jobs\TestCron::run {"id":67,"type":2,"exe_time":1599463122,"order_id":10000024,"status":2,"queue_status":2,"mch_order_id":"90806692346580992","args":"{\"ccode_url\":\"wxp\\/\\/f2f0XolMxgyUUdoYj10u2rzjKxuPmrkTemc5\",\"amount\":\"1\"}"} 
[2020-09-07 16:18:27] local.INFO: 請求上游介面===>https://www.test.com/test.php?project=test&id=10000024        返回狀態===>未轉賬        結果:{"data":"999","code":200}  
[2020-09-07 16:18:27] local.INFO: 未轉賬,修改訂單成功 [{"id":1,"mch_id":111,"ps_id":1,"mch_order_id":"2222","mch_notify_url":"http://notify.example.com","order_id":10000024,"order_status":4,"order_type":1,"ccode_url":"wxpay://1234jdkfjadjfkljadklf","amount":100,"create_time":"2020-09-04 16:18:11","update_time":"2020-09-07 16:18:27"}] 
  1. 確認資料庫是否修改成功
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章