消息提供和消费
package com.test; import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; public class ActiveMqTest { public static void main (String[] args) { producer(); // consumer(); } public static void producer () { try { String brokerURL = "tcp://localhost:61616"; String user = "admin"; String password = "admin"; ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, password, brokerURL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination queue = session.createQueue("demoQueue"); MessageProducer messageProducer = session.createProducer(queue); messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); String text = "hello activemq"; Message textMessage = session.createTextMessage(text); messageProducer.send(textMessage); session.close(); connection.close(); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } public static void consumer () { try { String brokerURL = "tcp://localhost:61616"; String user = "admin"; String password = "admin"; ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(user, password, brokerURL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination queue = session.createQueue("demoQueue"); MessageConsumer consumer = session.createConsumer(queue); Message message = consumer.receive(1000); if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); System.out.println( text ); } consumer.close(); session.close(); connection.close(); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } }
1、执行 producer 方法后在管理界面可以看到相关信息
2、执行 consumer 方法,消费消息