ActiveMQ实战之 Topic发布订阅消息

对于此类消息,其实就是指使用JMS中的发布订阅消息模型的消息,下面是一个简单的例子

消息发布者

01 package com.googlecode.garbagecan.jmsstudy.activemq.topic;
02  
03 import org.apache.activemq.ActiveMQConnectionFactory;
04  
05 import javax.jms.*;
06  
07 public class TopicPublisher {
08     public static void main(String[] args) throws JMSException {
09         ActiveMQConnectionFactory factory = newActiveMQConnectionFactory("tcp://localhost:61616");
10         Connection connection = factory.createConnection();
11         connection.start();
12          
13         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
14         Topic topic = session.createTopic("myTopic.messages");
15  
16         MessageProducer producer = session.createProducer(topic);
17         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
18  
19         while(true) {
20             TextMessage message = session.createTextMessage();
21             message.setText("message_" + System.currentTimeMillis());
22             producer.send(message);
23             System.out.println("Sent message: " + message.getText());
24  
25             try {
26                 Thread.sleep(1000);
27             catch (InterruptedException e) {
28                 e.printStackTrace();
29             }
30         }
31  
32 //      session.close();
33 //      connection.stop();
34 //      connection.close();
35     }
36 }
消息订阅者(消息消费者)
01 package com.googlecode.garbagecan.jmsstudy.activemq.topic;
02  
03 import org.apache.activemq.ActiveMQConnectionFactory;
04  
05 import javax.jms.*;
06  
07 public class TopicSubscriber {
08     public static void main(String[] args) throws JMSException {
09         ActiveMQConnectionFactory factory = newActiveMQConnectionFactory("tcp://localhost:61616");
10         Connection connection = factory.createConnection();
11         connection.start();
12          
13         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
14         Topic topic = session.createTopic("myTopic.messages");
15  
16         MessageConsumer consumer = session.createConsumer(topic);
17         consumer.setMessageListener(new MessageListener() {
18             public void onMessage(Message message) {
19                 TextMessage tm = (TextMessage) message;
20                 try {
21                     System.out.println("Received message: " + tm.getText());
22                 catch (JMSException e) {
23                     e.printStackTrace();
24                 }
25             }
26         });
27 //      session.close();
28 //      connection.stop();
29 //      connection.close();
30     }
31 }
分别运行两个类,就可以看到Publisher发布的类,Subscriber都可以接受到。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值