說明
前面介紹過ActiveMQ 的p2p(點對點)模式,p2p模式只允許一條消息給一個消費者使用,能夠保證消息不被重複消費(開啓事務時需要特殊處理才能保證)。今天我再介紹一種發佈訂閱模式,即一條消息能夠同時讓多個消費者同時消費,只要消費者訂閱了topic消息,那麼只要有消息發送過來,所有訂閱了topic的消費者能同時接收到,但是這個需要保證消費者實時在線。
依賴
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.10</version>
</dependency>
1.生產者:
public class TopicSender {
public static void main(String[] args) throws JMSException {
// 1. 建立工廠對象
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_BROKER_URL,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
"tcp://localhost:61616");
//2. 從工廠裏獲取一個連接
Connection connection = factory.createConnection();
connection.start();
//3. 從連接中獲取Session(會話)
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //第一個參數爲是否開啓事務
//4. 從會話中獲取目的地(Destination),消費者會從這個目的地取消息
Destination topic = session.createTopic("lance");
//5. 從會話中創建消息提供者
MessageProducer producer = session.createProducer(topic);
int i = 1;
try {
while (i <= 20) {
//從會話中創建文本消息(也可以創建其它類型的消息體)
TextMessage textMessage = session.createTextMessage("hello" + i);
producer.send(textMessage);
i++;
}
} catch (JMSException e) {
e.printStackTrace();
} finally {
// 關閉連接
connection.close();
}
System.out.println("exit");
}
}
2.消費者:
public class TopicRecviver {
public static void main(String[] args) throws JMSException {
// 1. 建立工廠對象
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
ActiveMQConnectionFactory.DEFAULT_BROKER_URL,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
"tcp://localhost:61616");
//2. 從工廠裏獲取一個連接
Connection connection = factory.createConnection();
connection.start();
//3. 從連接中獲取Session(會話)
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //第一個參數爲是否開啓事務
//4. 從會話中獲取目的地(Destination),消費者會從這個目的地取消息
Destination topic = session.createTopic("lance");
//5. 從會話中創建消息提供者
MessageConsumer consumer = session.createConsumer(topic);
//6. 持續的消費
try {
while (true) {
TextMessage textMessage = (TextMessage) consumer.receive();
System.out.println("消費:" + textMessage.getText());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉連接
connection.close();
}
}
}