topic:发布订阅:一个消息可以有多个消费者同时消费;生产者和消费者有时间上的依赖性;也就是当生产者发送消息时,应至少有一个消费者。
新建四个类
package com.etoak.topic;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class TopicListener implements MessageListener {
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage)message;
try {
System.out.println(textMessage.getText().toString());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
package com.etoak.topic;
import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;
public class HelloPublisher {
public static void main(String[] args) throws Exception{
ConnectionFactory factory = new ActiveMQConnectionFactory(null,null,"tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("topic");
MessageProducer producer = session.createProducer(topic);
TextMessage message = session.createTextMessage("测试topic消息");
producer.send(message);
producer.close();
session.close();
connection.close();
System.out.println("发送完成辽~~~");
}
}
package com.etoak.topic;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
public class HelloSubscriber {
public static void main(String[] args) throws Exception{
ConnectionFactory factory = new ActiveMQConnectionFactory(null,null,"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 TopicListener());
}
}
package com.etoak.topic;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
public class HelloSubscriber2 {
public static void main(String[] args) throws Exception{
ConnectionFactory factory = new ActiveMQConnectionFactory(null,null,"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 TopicListener());
}
}
运行
生产者发送消息的时候,必须至少有一个消费者,如果先发送消息,在运行消费者的话,运行者是接受不到消息的