Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
Software Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Distributed Message Service/ Best Practices/ Filtering Messages by Message Label

Filtering Messages by Message Label

Updated on 2023-11-30 GMT+08:00

Overview

In an actual scenario, messages stored in a queue may contain different practical purposes. If the messages are not differentiated, consumers will pull messages in sequence until the consumption of all messages is complete.

If consumers are interested only in a certain type of messages, consumption of all messages will affect the processing efficiency.

Optimization Solution

DMS provides the message label capability. A producer can provide one or more labels for each message. Messages are filtered based on the label content to ensure that consumers only consume the message type that they are interested in.

For example, in a financial scenario, multiple types of messages may be generated in a transaction, such as a stock, fund, and loan. These messages are transferred to different processing systems, such as the stock system, fund system, loan system, and real-time analysis system, through business topics. However, the fund system concerns only messages of the fund type, and the real-time analysis system may need to obtain all types of messages.

When producing a message, the producer adds a label to each message. When the consumer pulls messages, the consumer determines whether to obtain only messages with a specific label. This improves the message consumption efficiency, as shown in Figure 1.

Figure 1 Consumption of messages with labels
NOTICE:

DMS standard queues and FIFO queues support the message label function. Kafka queues do not support this function.

Sample Code

NOTICE:

The following describes only the codes related to the message label. To run the entire demo, download the complete sample code package and refer to the DMS Development Guide for deploying and running the code.

The example provides code based on the HTTP RESTful interface. For details about the APIs, see the Distributed Message Service API Reference in Help Center.

Sample code for message label design:

package com.cloud.dms;

import java.net.URL;
import java.util.Properties;
import com.cloud.dms.access.AccessServiceUtils;

public class DMSHttpClient
{
    private static String endpointUrl = "";

    private static String region = "";

    private static String serviceName = "dms";

    private static String aKey = "";

    private static String sKey = "";

    private static String projectId = "546e52331ea74cd49722fda4fb23bf55";

    private static String queueId = "39cd8dcb-b901-43b4-9ea1-48730e9adc58";

    private static String queueGroupId = "g-ae8ed05f-464c-452c-9e37-d3bdd081000d";

    /*
     * Read Configure File And Initialize Variables
     */
    static
    {
        URL configPath = ClassLoader.getSystemResource("dms-service-config.properties");
        Properties prop = AccessServiceUtils.getPropsFromFile(configPath.getFile());
        region = prop.getProperty(Constants.DMS_SERVICE_REGION);
        aKey = prop.getProperty(Constants.DMS_SERVICE_AK);
        sKey = prop.getProperty(Constants.DMS_SERVICE_SK);
        endpointUrl = prop.getProperty(Constants.DMS_SERVICE_ENDPOINT_URL);
        if (endpointUrl.endsWith("/"))
        {
            endpointUrl = endpointUrl + "v1.0/";
        }
        else
        {
            endpointUrl = endpointUrl + "/v1.0/";
        }
        projectId = prop.getProperty(Constants.DMS_SERVICE_PROJECT_ID);
    }
    
    public static void main(String[] args)
    {
        runAllApiMethods();
    }
    
    public static void runAllApiMethods()
    {
        MsgAttri msg = new MsgAttri();
        msg.setaKey(aKey);
        msg.setEndpointUrl(endpointUrl);
        msg.setProjectId(projectId);
        msg.setQueueId(queueId);
        msg.setsKey(sKey);
        msg.setRegion(region);
        msg.setServiceName(serviceName);
        msg.setMsgLimit("10");
        msg.setGroupId(queueGroupId);
        /**
         *          * Construct producers and four types of consumers and set labels that they are interested in.
         */
        MsgProducer msgProducer = new MsgProducer(msg);
        MsgConsumer stock = new MsgConsumer(msg, "stock");
        MsgConsumer fund = new MsgConsumer(msg, "fund");
        MsgConsumer loan = new MsgConsumer(msg, "loan");
        MsgConsumer all = new MsgConsumer(msg, null);
        /**
         * Create threads, simulate production and consumption behaviors, and set thread names for differentiation.
         */
        Thread producer = new Thread(msgProducer);
        Thread stockThread = new Thread(stock);
        Thread fundThread = new Thread(fund);
        Thread loanThread = new Thread(loan);
        Thread alls = new Thread(all);
        producer.setName("producer");
        stockThread.setName("stock");
        fundThread.setName("fund");
        loanThread.setName("loan");
        alls.setName("Analysis");
        /**
         * Start threads.
         */
        producer.start();
        stockThread.start();
        fundThread.start();
//        loanThread.start();
//        alls.start();
    }
}

Sample code for producing messages:

package com.cloud.dms;

import static com.cloud.dms.ApiUtils.constructTempMessages;
import static com.cloud.dms.ApiUtils.sendMessages;

import java.util.concurrent.TimeUnit;

public class MsgProducer implements Runnable{
    private MsgAttri msgAttri;

    public MsgProducer(MsgAttri msg) {
       this.msgAttri = msg;
    }
    
    public void run() {
       while (true)
       {
           /**
           * Simulate producers to construct messages. JSON contains the stock, fund, and loan messages.
           **/
           String messages = constructTempMessages(null);
           sendMessages(messages, this.msgAttri);
           try
           {
              TimeUnit.SECONDS.sleep(1);
           }
           catch (InterruptedException e) {
           }
       }
    }
}

Sample code for consuming messages:

 
package com.cloud.dms;

import static com.cloud.dms.ApiUtils.acknowledgeMessages;
import static com.cloud.dms.ApiUtils.consumeMessages;
import static com.cloud.dms.ApiUtils.parseHandlerIds;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MsgConsumer implements Runnable{
    
    private MsgAttri msgAttri;
    
    private String tag;

    /**
    *Construct a function to obtain the label that consumers are interested in.
    **/
    public MsgConsumer(MsgAttri msg, String tag) {
       this.tag = tag;
       this.msgAttri = msg;
    }
    
    public void run() {
       while (true)
       {
           /**
           *Consume messages and obtain messages with the label.
           **/
           ResponseMessage consumeMessagesResMsg = consumeMessages(msgAttri, tag);
           /**
           *Parse messages.
           **/
           if (consumeMessagesResMsg.getStatusCode() == 200)
           {
              List<String> msgStrings = ApiUtils.decodeMsg(consumeMessagesResMsg);
              /**
              *Simulate message processing and print messages with the label.
              **/
              for (String s : msgStrings)
              {
                  System.out.println("Thread--"+ Thread.currentThread().getName() + "--Message Body is: "+ s);
              }
              /**
              * Confirm message consumption.
              **/
              ArrayList<String> handlerIds = parseHandlerIds(consumeMessagesResMsg);
              if (handlerIds.size() > 0)
              {
                  acknowledgeMessages(handlerIds, msgAttri);
              }
           }
           else
           {
              System.out.println("Http Response Code is: "
                     + consumeMessagesResMsg.getStatusCode() + "\n Http Body is: "
                     + consumeMessagesResMsg.getBody());
              
           }
           try
           {
              TimeUnit.SECONDS.sleep(2);
           } 
           catch (InterruptedException e) 
           {
           }
       }
    }
}

Running Results of Sample Code

The loan thread has specified the tag (loan) and therefore can consume only messages with the loan label.

The fund and stock threads can consume only the specified messages.

The analysis thread does not specify a label and can consume all messages in the topic.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback