2016年2月19日星期五

ActiveMQ_016:Message Group 使用例子

环境:OS X EI Capitan 10.11.3 + ActiveMQ 5.13.0

发送消息时,可以设置组别,Message Group 可以让消息消费者按组消费消息,同一组的消息只能由一个消费者消费。
Broker 会随机计算出哪个消费者消费哪个组的信息。

如果发送消息时,不想再设置组别,可以设置值为-1。

1. Queue_Sender_Message_Group1_AutoAck_NonPeresistent.java

package com.travelsky.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;

public class Queue_Sender_Message_Group1_AutoAck_NonPeresistent {

    private static final int SEND_NUMBER = 5;

    public static void main(String[] args) {

        // ConnectionFactory:连接工厂,JMS用它创建连接
        ConnectionFactory connectionFactory;
        // Connection:JMS客户端到JMS Provider的连接
        Connection connection = null;
        // Session:一个发送或接收消息的线程
        Session session;
        // Destination:消息的目的地
        Destination destination;
        // MessageProducer: 消息生产者
        MessageProducer producer;
        //构造ConnectionFactory实例对象,此处采用ActiveMq的实现
        connectionFactory = new ActiveMQConnectionFactory(
                "admin",
                "admin",
                "failover:(tcp://127.0.0.1:61616)");

        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("FirstQueue");
            producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            sendMessage(session, producer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection) {
                    connection.close();
                }
            } catch (Throwable ignore) {
            }
        }
    }

    public static void sendMessage(Session session, MessageProducer producer)
            throws Exception {
        for (int i = 1; i <= SEND_NUMBER; i++) {
            TextMessage message = session
                    .createTextMessage("Msg_group_1 ActiveMq发送的消息" + i);
            message.setStringProperty("JMSXGroupID", "Msg_group_1");
            // message.setIntProperty(“JMSXGroupSeq”, -1);
            //Thread.sleep(5000);
            System.out.println("Msg_group_2 发送消息:" + "ActiveMq 发送的消息" + i);
            producer.send(message);          
        }
    }
}


使用例子

参考文献:
1. http://marcelojabali.blogspot.com/2011/11/load-balanced-ordered-message.html

没有评论: