1.activemq 是Apache软件基金会所研发的开放源代码消息中间件;由于ActiveMQ是一个纯Java程序,因此只需要操作系统支持Java虚拟机,ActiveMQ便可执行。
1.生产者 public class Producer { private static final String url = "tcp://127.0.0.1:61616"; private static final String topicName = "topic-test"; public static void main(String[] args) throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection= connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(topicName); MessageProducer messageProducer = session.createProducer(destination); for (int i = 0; i < 10; i++) { TextMessage textMessage = session.createTextMessage("test" + i); messageProducer.send(textMessage); System.out.println("发送消息:" + textMessage); } connection.close(); } }
2.消费者
public class Consumer { private static final String url = "tcp://127.0.0.1:61616"; private static final String topicName = "topic-test"; public static void main(String[] args) throws JMSException { ActiveMQConnectionFactory activemqApplication = new ActiveMQConnectionFactory(url); Connection connection = activemqApplication.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(topicName); MessageConsumer messageConsumer = session.createConsumer(destination); messageConsumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { System.out.println("接受消息==[" + ((TextMessage)message).getText() + "]"); } catch (JMSException e) { e.printStackTrace(); } } }); } }