Top Posts
Gửi mail trong Magento 2 – Đính kèm...
Tạo grid trong Magento 2 sử dụng block
Tạo form admin sử dụng block
Cách sử dụng insertListing trong Magento 2
Compile LESS file với Grunt trong Magento 2
Magento 2 get product image url
Format price với currency trong Magento 2
Magento 2 Add URL Rewrite programmatically
Magento 2 Upload image admin form
Magento 2 Create Category Attribute
vi-magento.com
  • Magento 2
    • Magento 2 cơ bản
    • Bài tập Magento 2
    • Magento 2 Api
  • PHP
  • JavaScript
  • Cơ sở dữ liệu
    • Học MongoDB
    • SQL Server
    • Mysql
    • Học Oracle
    • SQLite
  • Liên hệ
  • Trắc nghiệm Magento 2
Trang chủ Lập trình Magento 2Magento cơ bản Message queue trong magento 2
Magento cơ bản

Message queue trong magento 2

bởi admin 24/01/2021
bởi admin 24/01/2021 0 Bình luận 1532 xem

Hiểu đơn giản thì cơ chế của message queue sẽ thực hiện thông qua cron job. Đầu tiên chúng ta phải gửi message đến queue có thể kèm theo tham số và queue sẽ thực hiện công việc của nó. Trong bài viết này chúng ta sẽ cùng nhau tìm hiểu về cách tạo một queue trong Magento 2.

Để tạo một queue trong Magento 2, đầu tiên chúng ta cần phải tạo 4 file .xml trong thư mục <vendor>/<module>/etc/:

Danh mục

  1. communication.xml
  2. queue_consumer.xml
  3. queue_topology.xml
  4. queue_publisher.xml
  5. Thêm message vào queue
  6. Message queue Status
  7. Thực thi message

communication.xml

ViMagento/HelloWorld/etc/communication.xml

1
2
3
4
5
6
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Communication/etc/communication.xsd">
    <topic name="vimagento.queue.topic" request="string">
        <handler name="vimagentoExample"  type="ViMagento\HelloWorld\Model\Queue\Consumer" method="process" />
    </topic>
</config>

Topic element

PARAMETER MÔ TẢ
name Một chuỗi duy nhất định danh cho topic name. Topic name nên là các chuỗi nhỏ được phân cách nhau bởi dấu chấm.
request Kiểu dữ liệu của topic name (string, array).
response Xác định kiểu dữ liệu của phản hồi. Tham số này là bắt buộc nếu bạn định nghĩa một topic đồng bộ. Nếu không hãy bỏ qua nó.
schema Interface mô tả cấu trúc của message queue. Định dạng phải là <module>\Api\<ServiceName>::<methodName>.
Topic element

Handler element

Đây là phần xác định class sẽ xử lý logic.

PARAMETER MÔ TẢ
name Tên định danh cho handler và là duy nhất.
type Class hoặc interface sẽ xử lý logic cho topic.
method Phương thức sẽ thực thi khi queue chạy.
disabled Xác định xem handler có bị vô hiệu hóa hay không. Mặc định là false.
Handler element

Sau đó các bạn tạo class handler đã khai báo ở trên.

ViMagento\HelloWorld\Model\Queue\Consumer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
 
namespace ViMagento\HelloWorld\Model\Queue;
 
class Consumer
{
    /**
     * @param $data
     */
    public function process($data)
    {
        // $data là tham số được truyền vào khi bạn gửi một message vào queue
        // Your logic
    }
}

queue_consumer.xml

ViMagento/HelloWorld/etc/queue_consumer.xml có thể chứa nhiều node consumer.

1
2
3
4
5
6
7
8
9
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/consumer.xsd">
    <consumer name="vimagento.queue.topic"
              queue="vimagento.queue.topic"
              connection="db"
              maxMessages="5000"
              consumerInstance="Magento\Framework\MessageQueue\Consumer"
              handler="ViMagento\HelloWorld\Model\Queue\Consumer::process"/>
</config>
ATTRIBUTE MÔT TẢ
name (required) Tên của consumer.
queue (required) Xác định queue name để gửi message.
handler Xác định class và method sẽ thực thi message. Có định dạng <Vendor>\Module\<ServiceName>::<methodName>.
consumerInstance Tên class name Magento sẽ xử lý message.
connection For AMQP connections, the connection name must match the connection attribute in the queue_topology.xml file. Otherwise, the connection name must be db.
maxMessages Xác định số lượng message tối đa.
maxIdleTime Xác định thời gian đợi tối đa (tính bằng giây) để thực thi đỗi với một queue mới. Mặc định: null
consumer element

queue_topology.xml

ViMagento/HelloWorld/etc/queue_topology.xml

1
2
3
4
5
6
7
8
9
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/topology.xsd">
    <exchange name="magento-db" type="topic" connection="db">
        <binding id="processViMagentoExampleToQueueBinding"
                 topic="vimagento.queue.topic"
                 destinationType="queue"
                 destination="vimagento.queue.topic"/>
    </exchange>
</config>

queue_publisher.xml

1
2
3
4
5
6
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/publisher.xsd">
    <publisher topic="vimagento.queue.topic">
        <connection name="db" exchange="magento-db" />
    </publisher>
</config>

Sau đó các bạn chạy câu lệnh php bin/magento setup:upgrade để thêm queue đã tạo vào hệ thống. Nếu thành công các bạn kiểm tra trong bảng queue sẽ thấy topic name vừa tạo. Ngược lại nếu không có bạn cần kiểm tra lại 4 file đã tạo.

Bảng queue chứa danh sách các queue trong hệ thống
Bảng queue chứa danh sách các queue trong hệ thống

Thêm message vào queue

Một ví dụ khi bạn generate coupon trong cart price rule, bạn sẽ thấy chúng sẽ không generate ngay mà chúng sẽ thêm request của chúng ta vào queue và cron sẽ chạy chúng.

Thêm message vào queue
Thêm message vào queue

Tương tự như trên chúng ta cũng sẽ tạo một Controller để thực hiện thêm message vào queue.

ViMagento/HelloWorld/Controller/Adminhtml/Index/Index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
 
namespace ViMagento\HelloWorld\Controller\Adminhtml\Index;
 
use Magento\Backend\App\Action;
 
/**
* Class Index
* @package ViMagento\HelloWorld\Controller\Adminhtml\Index
*/
class Index extends \Magento\Backend\App\Action
{
    const ADMIN_RESOURCE = 'ViMagento_HelloWorld::add_queue';
 
    const TOPIC_NAME = 'vimagento.queue.topic';
 
    /**
     * @var \Magento\Framework\MessageQueue\PublisherInterface
     */
    protected $publisher;
 
    /**
     * @var \Magento\Framework\Serialize\Serializer\Json
     */
    protected $json;
 
    /**
     * Index constructor.
     * @param \Magento\Framework\MessageQueue\PublisherInterface $publisher
     * @param \Magento\Framework\Serialize\Serializer\Json $json
     * @param Action\Context $context
     */
    public function __construct(
        \Magento\Framework\MessageQueue\PublisherInterface $publisher,
        \Magento\Framework\Serialize\Serializer\Json $json,
        Action\Context $context
    ) {
        $this->publisher = $publisher;
        $this->json = $json;
        parent::__construct($context);
    }
 
    public function execute()
    {
        try {
            // Dữ liệu mà bạn muốn thêm vào queue cũng là tham số ở hàm thực thi process()
            $data = [1, 2, 3];
            // Thêm vào queue, vì tôi đã khai báo type là string ở file communication.xml
            // nên phải chuyển data sang kiểu string
            $this->publisher->publish(self::TOPIC_NAME, $this->json->serialize($data));
            $this->messageManager->addSuccessMessage(__('Message is added to queue, wait to get your coupons soon'));
        } catch (\Exception $exception) {
            $this->messageManager->addErrorMessage(__($exception));
        }
        return $this->_redirect('*/*/redirect');
    }
}

Sau đó tôi chạy controller thành công và kiểm tra bảng queue_message (chứa các message trong hàng đợi) sẽ có một record tương ứng tôi vừa thêm vào.

queue message
queue message

Message queue Status

Sau khi đã thêm message vào hàng đợi, cron job sẽ thực thi method process($data) mà chúng ta đã tạo ở đầu bài viết, với $data là body trong bảng queue_message. Để xem message của bạn đã được thực thi thành công hay chưa bạn có thể xem ở bảng queue_message_status.

queue_message_status
queue_message_status

Bạn có thể xem tất cả status của message queue tại: Magento\MysqlMq\Model\QueueManagement

message queue status
message queue status

Thực thi message

Message sẽ được thực thi bởi cron job được cấu hình trong Magento/MessageQueue/etc/crontab.xml

config cron execute message queue
config cron execute message queue

Bạn cũng có thể thực thi message queue với CLI bằng câu lệnh:

1
php bin/magento queue:consumers:start [topic_name]

Ví dụ: php bin/magento queue:consumers:start vimagento.queue.topic

Xem thêm tại devdocs của magento: https://devdocs.magento.com/guides/v2.4/extension-dev-guide/message-queues/config-mq.html

Xem thêm:

Hướng dẫn tạo cron job trong Magento 2

Danh sách các bài viết về magento 2

magentomagento 2message queuemessagequeue
Chia sẻ
0
FacebookSkype
Bài trước
Quản lý indexer – các command cần thiết
Bài tiếp theo
Theme trong Magento 2

Related Posts

Sử dụng Ajax với Knockout JS trong Magento...

27/09/2020

Tạo system.xml trong Magento 2

19/08/2020

Tạo Custom Indexer Trong Magento 2

03/07/2021

[Magento 2 cơ bản] Hướng dẫn thêm một...

24/08/2020

Quản lý indexer – các command cần thiết

23/01/2021

Danh sách các validate rule trong Magento 2

19/09/2020

Layout, Block, Template trong Magento 2

15/08/2020

Compile LESS file với Grunt trong Magento 2

05/08/2021
0 0 vote
Đánh giá
Login
guest
guest
0 Comments
Inline Feedbacks
View all comments

Bài viết cùng chủ đề

  • Hướng dẫn cài đặt Magento 2.4 trên Ubuntu

  • Hướng dẫn tạo Module trong Magento 2

  • Tạo Controller trong Magento 2 chi tiết nhất

  • Layout, Block, Template trong Magento 2

  • Layout trong Magento 2 – Hướng dẫn chi tiết

  • Plugin trong Magento 2 – Hướng dẫn chi tiết

  • Magento 2 thay đổi tên product sử dụng Plugin

  • Tạo bảng trong Magento 2 với Setup script

  • Tạo bảng với db_schema.xml trong Magento 2

  • Hướng dẫn cài đặt xdebug cho phpstorm trên ubuntu

  • Model, Resource Model và Collection trong Magento 2

  • Data Patch trong Magento 2 – Hướng dẫn chi tiết

  • Thêm Product Attribute Trong Magento 2

  • ACL trong Magento 2 – Hướng dẫn tạo ACL

  • Tạo Menu Admin trong Magento 2

  • Tạo system.xml trong Magento 2

  • Tạo form admin trong Magento 2 với Ui Component

  • Tạo Grid trong Magento 2 với Ui Component

  • Thêm, Xóa, Sửa dữ liệu trong Magento 2

  • Magento 2 Thêm Action Column trong Admin Grid

  • [Magento 2 cơ bản] Tìm hiểu về Events và Observers trong Magento 2

  • Tất tần tật danh sách các Events trong Magento 2

  • Bóc mẽ cách Magento tổ chức, thiết kế sản phẩm

  • Magento 2 Hướng dẫn tạo Cron Job

  • [Magento 2 cơ bản] Hướng dẫn thêm một Customer Attribute trong Magento 2

  • Magento 2 Đối tượng Factory

  • Cài đặt HTTPS (SSL) cho localhost dễ hiểu

  • Magento 2 Các loại join và giải thích chi tiết

  • Magento 2 Dependency Injection là gì? Tại sao phải sử dụng Dependency Injection?

  • Hướng dẫn thêm custom field ở trang checkout trong Magento 2

  • Sắp xếp danh sách sản phẩm theo price, name trong Magento 2

  • Magento 2 Add custom column into sales order grid

  • Magento 2 Cách sử dụng Knockout Js trong custom templates

  • Magento 2 Tìm hiểu về 6 loại product

  • Hướng dẫn thêm product type trong Magento 2

  • Các cách để override templates trong Magento 2

  • Widget là gì? Hướng dẫn tạo custom widget trong Magento 2

  • Tạo Admin User thông qua Command line trong Magento 2

  • Hướng dẫn lấy đường dẫn hiện tại, media, static trong Magento 2

  • Hướng dẫn sắp xếp danh sách sản phẩm theo lượt view trong Magento 2

  • Tìm hiểu về di.xml trong Magento 2

  • Filter Collection trong Magento 2

  • Các hàm xử lý dữ liệu trong Magento 2

  • Translate trong Magento 2

  • Tạo Source model trong Magento 2

  • Frontend model trong Magento 2 (system.xml)

  • Backend model trong Magento 2 (system.xml)

  • Magento 2 cơ bản – tự học magento 2

  • Tạo popup modal trong Magento 2

  • Thêm Custom Validate Rule trong Magento 2

  • Danh sách các validate rule trong Magento 2

  • Lợi ích và cách sử dụng Jquery trong Magento 2

  • Lưu custom data vào bộ nhớ cache | Magento 2

  • Truy vấn SQL trong Magento 2

  • Cách tạo Cronjob trong Magento2

  • Sử dụng Ajax với Knockout JS trong Magento 2

  • Sử dụng Ajax trong Magento 2

  • EAV trong Magento 2 | Magento 2 cơ bản

  • Hiểu Về Repository trong Magento 2

  • Hướng dẫn customize Magento 2 commands

  • Cách cài đặt zsh và zsh-autosuggestions trên Ubuntu

  • Thêm Multi Select Filter trong Admin Grid

  • Tạo admin grid với dữ liệu của nhiều table

  • Tìm hiểu về indexing trong magento 2

  • Quản lý indexer – các command cần thiết

  • Theme trong Magento 2

  • Linux Là Gì?

  • Phân biệt Salable Quantity và Quantity trong Magento 2

  • Magento 2 Tìm hiểu về Proxy

  • EAV Attribute trong Magento 2

  • Cài đặt Magento 2.4 trên windows

  • Magento 2 – Kiểm tra customer đã đăng nhập hay chưa?

  • Thêm Command Console Trong Magento 2

  • Các lệnh cơ bản trong Magento 2 mà lập trình viên cần phải biết

  • Tạo Custom Indexer Trong Magento 2

  • Magento 2 Create Category Attribute

  • Magento 2 Upload image admin form

  • Magento 2 Add URL Rewrite programmatically

  • Format price với currency trong Magento 2

  • Magento 2 get product image url

  • Compile LESS file với Grunt trong Magento 2

  • Cách sử dụng insertListing trong Magento 2

  • Tạo form admin sử dụng block

  • Tạo grid trong Magento 2 sử dụng block

  • Gửi mail trong Magento 2 – Đính kèm file

@2020 - All Right Reserved. vi-magento.com

vi-magento.com
  • Magento 2
    • Magento 2 cơ bản
    • Bài tập Magento 2
    • Magento 2 Api
  • PHP
  • JavaScript
  • Cơ sở dữ liệu
    • Học MongoDB
    • SQL Server
    • Mysql
    • Học Oracle
    • SQLite
  • Liên hệ
  • Trắc nghiệm Magento 2
wpDiscuz