1.创建Maven项目(jar
2.pom.xml文件引入依赖
<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-client</artifactId>
<version>5.13.4</version>
</dependency>
</dependencies>
3.创建消息发送者(订阅者模型
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/*
消息发送者(订阅者模型,发送
*/
public class SendsProducer {
public static void main(String[] args) throws Exception{
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.200.128:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("test-topic");
MessageProducer producer = session.createProducer(topic);
TextMessage textMessage = session.createTextMessage("tom");
producer.send(textMessage);
connection.close();
producer.close();
session.close();
}
}
4.创建消息接收者(这里我写了2个
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/*
消息接受者
*/
public class TopicConsumer1 {
public static void main(String[] args) throws Exception{
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.200.128:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("test-topic");
MessageConsumer consumer = session.createConsumer(topic);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("接受的消息1为:"+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
System.in.read();
connection.close();
consumer.close();
session.close();
}
}
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/*
消息接受者
*/
public class TopicConsumer2 {
public static void main(String[] args) throws Exception{
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.200.128:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("test-topic");
MessageConsumer consumer = session.createConsumer(topic);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("接收的消息2为:"+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
System.in.read();
connection.close();
consumer.close();
session.close();
}
}
5.先运行2个消息接收者,再运行消息发送者,查看
over ~