Alibaba Cloud Messaging Service Tutorial

Alibaba Cloud Messaging Service Tutorial

1. Description of project requirements

    Recently, the company has been continuously docking with the external system of customers, and order is one of the docking tasks. The company currently has a central system responsible for processing orders, but the sources of orders are all pulled from other systems through timed tasks. The previous version of the old system, which was perfected not long ago, joined the business of the mall, and also synchronized the orders of the external system, so it became the source of the orders. Now we need to change the order system, from the original pull order to actively receiving orders, so we use Alibaba Cloud's message service.

2. Project business design

    We have three systems related to orders: A. java mall system, B. ocs order center system; C. php mall system. Now system A can get all the order sources, so the message service is sent at the starting point of each order, that is, system A is the message producer. In the B system, we subscribe to the messages sent by the A system, so as to consume the messages and store the orders, that is, the B system is the message consumer.

3. Project MQ service configuration

    In the first blog, we learned that the mode of message queue is divided into two types: queue and topic, and we use the topic mode. Ali's message service is also very convenient to use, and you can configure it directly in the management console.

     1. Create a new topic

这里写图片描述

     2. Apply for release, i.e. message producer

这里写图片描述

     3. Apply for a subscription, that is, a message consumer

这里写图片描述

4. Project MQ Java SDK

     It is relatively simple to add mq to the project, and there is also a corresponding demo on the official website.

     1. Message producer tool class: Read the topic, producer and some keys configured in the message service console in the configuration file to create a message producer.

public OrderProducer getPlusOrderProducer() {

        if (orderProducer != null) {
            return orderProducer;
        }
        Properties producerProperties = new Properties();
        producerProperties.setProperty(PropertyKeyConst.ProducerId, Global.getConfig("PID_UQI_ORDER_UPLUS"));
        producerProperties.setProperty(PropertyKeyConst.AccessKey, Global.getConfig("ACCESS_KEY"));
        producerProperties.setProperty(PropertyKeyConst.SecretKey, Global.getConfig("SECRET_KEY"));
        producerProperties.setProperty(PropertyKeyConst.ONSAddr, Global.getConfig("ONSADDR"));
        orderProducer = ONSFactory.createOrderProducer(producerProperties);
        orderProducer.start();
        logger.debug("uplus订单生产者启动...");
        return orderProducer;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

     2. Push message business class: Get the instance of the message producer and send the message.

public void pushMsg(WmsOrder orderInfo) {
        //根据不同的tag选择推送不同的字段
        byte[] bytes = null;
        Message message = null;
        SendResult sendResult = null;
        OrderProducer producer = MqUtils.getInstance().getPlusOrderProducer();

        bytes = new Gson().toJson(orderInfo).getBytes();
        message = new Message(Global.getConfig("TID_UQI_ORDER_UPLUS"), Global.getConfig("TAG_UQI_ORDER_UPLUS"), bytes);
        try {
            sendResult = producer.send(message, Global.getConfig("TAG_UQI_ORDER_UPLUS"));
            // 发送消息,只要不抛异常就是成功
            if (sendResult != null) {
                logger.debug(new Date() + " 发送消息成功! Topic 是:" + message.getTopic() + " msgId 是: " + message.getMsgID() + " msgTag 是:" + message.getTag());
                logger.info("消息内容是" + message.getBody());
            }
        } catch (Exception e) {
            // 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理
            logger.debug(new Date() + " Send mq message failed. Topic is:" + message.getTopic());
            e.printStackTrace();
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

     3. Message consumer tool class: Read the topic, consumer and some keys configured in the message service console in the configuration file to create a message consumer.

public OrderConsumer getPlusOrderConsumer() {
        String topic = Global.getConfig("TID_UQI_ORDER_UPLUS");
        String subExpression = Global.getConfig("TAG_UQI_ORDER_UPLUS");
        Properties consumerProperties = new Properties();
        consumerProperties.setProperty(PropertyKeyConst.ConsumerId, Global.getConfig("CID_UQI_ORDER_UPLUS"));
        consumerProperties.setProperty(PropertyKeyConst.AccessKey, Global.getConfig("ACCESS_KEY"));
        consumerProperties.setProperty(PropertyKeyConst.SecretKey, Global.getConfig("SECRET_KEY"));
        consumerProperties.setProperty(PropertyKeyConst.ONSAddr, Global.getConfig("ONSADDR"));
        // 广播订阅方式设置
        consumerProperties.setProperty(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
        OrderConsumer orderConsumer = ONSFactory.createOrderedConsumer(consumerProperties);

        orderConsumer.subscribe(topic, subExpression, new MessageOrderListener() {
            @Override
            public OrderAction consume(Message message, ConsumeOrderContext context) {

                try {
                    logger.info(new String(message.getBody(), "UTF-8"));

                    Gson gson = new Gson();
                    WmsOrder wmsOrder = gson.fromJson(new String(message.getBody(), "UTF-8"), WmsOrder.class);

                    final WmsOrderService wmsOrderService = FrameSpringBeanUtil.getBean(WmsOrderService.class);

                    wmsOrderService.synUplusOrder(wmsOrder);
                    return OrderAction.Success;
                } catch (Exception e) {
                    e.printStackTrace();
                    return OrderAction.Suspend;
                }
            }
        });
        orderConsumer.start();
        logger.info("订单消费者启动...");
        return orderConsumer;
    }
  • 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

     4. Add a listener, start the consumer when the project starts, and configure the listener in web.xml

public class ConfigListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent context) {
    }

    @Override
    public void contextInitialized(ServletContextEvent context) {

        //MQ订单导入
        MqConsumerUtil.getInstance().getPlusOrderConsumer();

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
<listener>
        <listener-class>com.uqiauto.ocs.listener.ConfigListener</listener-class>
</listener>
  • 1
  • 2
  • 3

V. Summary of the use of project MQ

     使用消息服务,这过程中也是比较顺利的,在这次负责订单中心mq的接入过程中,也学习到了很多东西,所以,做完后花个时间做个总结整理还是很有必要的。

阿里云消息服务使用教程开始学习

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324841336&siteId=291194637