lumen 8.0 使用 rabbitmq 佇列

charliecen 發表於 2020-10-26

lumen rabbitmq 使用

安裝rabbitmq

在Windows先安裝,需要準備的資源如下:

  1. erlang
  2. rabbitmq-server

啟動服務

win+R 輸入services.msc,檢視服務RabbitMQ, 啟動該服務。

安裝php amqp擴充套件

下載地址

修改php.ini

檔案php_amqp.dll,php_amqp.pdb拷貝到php7.x.xext目錄中,並修改配置檔案php.ini

extension="D:\phpstudy_pro\Extensions\php\php7.4.3nts\ext\php_amqp.dll"

注意,記得重啟nginx

安裝外掛

composer require vladimir-yuldashev/laravel-queue-rabbitmq

新增註冊bootstrap/app.php

// mq註冊
$app->register(VladimirYuldashev\LaravelQueueRabbitMQ\LaravelQueueRabbitMQServiceProvider::class);

配置config/app.php

 'rabbitmq'  => [
            'driver'        =>  'rabbitmq',
            'queue'         =>  env('RABBITMQ_QUEUE','default'),
            'connection'    =>  \PhpAmqpLib\Connection\AMQPLazyConnection::class,
            'hosts'         =>  [
                [
                    'host'      =>  env('RABBITMQ_HOST', '127.0.0.1'),
                    'port'      =>  env('RABBITMQ_PORT', '5672'),
                    'user'      =>  env('RABBITMQ_USER', 'guest'),
                    'password'  =>  env('RABBITMQ_PASSWORD', 'guest'),
                    'vhost'     =>  env('RABBITMQ_VHOST', '/'),
                ]
            ],

            'options'   =>  [
                'ssl_options' => [
                    'cafile'        => env('RABBITMQ_SSL_CAFILE', null),
                    'local_cert'    => env('RABBITMQ_SSL_LOCALCERT', null),
                    'local_key'     => env('RABBITMQ_SSL_LOCALKEY', null),
                    'verify_peer'   => env('RABBITMQ_SSL_VERIFY_PEER', true),
                    'passphrase'    => env('RABBITMQ_SSL_PASSPHRASE', null),
                ],
            ]
        ]

配置.env

QUEUE_CONNECTION=rabbitmq  #修改一下

RABBITMQ_HOST=127.0.0.1  #要連線的主機名
RABBITMQ_PORT=5672         #埠號
RABBITMQ_VHOST=/
RABBITMQ_LOGIN=guest       #mq登入名
RABBITMQ_PASSWORD=guest     #mq登入密碼
RABBITMQ_QUEUE=cenhuqing         #mq連線的名稱(隨便寫)

建立任務類

php artisan make:job TestQueue

具體程式碼如下:

<?php

namespace App\Jobs;

use App\Models\Post;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class TestQueue implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    private $data;

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

    public function handle() {
        // 插入資料
        Post::create($this->data);
    }
}

建立控制器

<?php

namespace App\Http\Controllers;

use App\Jobs\TestQueue;

class ExampleController extends Controller
{
    public function store_with_mq(Request $request)
    {
        $message = [
            'title.required'    => '請輸入標題',
            'title.string'      => '標題必須為字串',
            'title.max'         => '標題最多 :max 字元',
            'content.required'  => '請輸入內容',
            'content.string'    => '內容必須為字串'
        ];
        $validator = Validator::make($request->input(), [
            'title'     => 'required|string|max:10',
            'content'   => 'required|string',
        ], $message);

        if ($validator->fails()) {
            foreach($validator->errors()->getMessages() as $error) {
                return resp(Code::CreateUserFailed, $error[0]);
            }
        }

        $attributes = $request->only('title', 'content');
        $attributes['user_id'] = 1; //auth()->user()->id;
        // 加入mq佇列中
        $this->dispatch(new TestQueue($attributes));
        return resp(Code::CreatePostsSuccess, Msg::CreatePostsSuccess);
    }
}

建立路由

$router->post('/posts', '[email protected]_with_mq');

啟動佇列

php artisan rabbitmq:consume
[2020-10-26 14:07:40][5b482036-1573-4ed3-a081-fc33565ee102] Processing: App\Jobs\TestQueue
[2020-10-26 14:07:40][5b482036-1573-4ed3-a081-fc33565ee102] Processed:  App\Jobs\TestQueue

請求測試

curl --location --request POST 'localhost:84/posts' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: laravel_session=go3wRgLpOKusZYLYz2ik27H1ZSjk0E5VxBYLliOI' \
--data-urlencode 'title=123' \
--data-urlencode 'content=123'

檢視資料庫

SELECT * FROM posts WHERE title = 123

    id  user_id  title   content  comment_count           created_at           updated_at  deleted_at  
------  -------  ------  -------  -------------  -------------------  -------------------  ------------
   203        1  123     123                  0  2020-10-26 22:07:40  2020-10-26 22:07:40        (NULL)
本作品採用《CC 協議》,轉載必須註明作者和本文連結