记录下自己学习activeMQ发布订阅模型的过程:
发布者Pub:
package com.mq.pubSub;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import com.mq.constant.Create_Type;
import com.mq.p2p.ConnUtils;
public class Pub {
// MessageProducer:消息发送者
private static MessageProducer Pubproducer;
public void pubSendMessage() throws JMSException, InterruptedException{
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("topic");
Pubproducer = session.createProducer(topic);
Pubproducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
while(true){
TextMessage message = session.createTextMessage();
message.setText("Hello Topic_MQ "+System.currentTimeMillis());
// 发送消息到目的地方
System.out.println("Hello Topic_MQ "+System.currentTimeMillis());
Pubproducer.send(message);
Thread.sleep(5000);
}
}
public static void main(String[] args) throws JMSException, InterruptedException {
new Pub().pubSendMessage();
}
}
订阅者订阅主题(Sub):
package com.mq.pubSub;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
public class Sub {
public void TopicReceive() throws Exception{
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("topic");
MessageConsumer consumer = session.createConsumer(topic);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage tm = (TextMessage) message;
try {
System.out.println("Received message: " + tm.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) throws Exception {
new Sub().TopicReceive();
}
}

本文介绍了一种基于ActiveMQ的消息中间件实现的发布订阅模型。通过具体的代码示例展示了如何创建发布者发送消息到主题,以及如何设置订阅者接收这些消息。发布者使用NON_PERSISTENT传递模式提高效率,并通过无限循环不断发送带有时间戳的消息。
1254

被折叠的 条评论
为什么被折叠?



