package com.sunny.producer; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; public class ProducerTest { public static void main(String[] args) throws JMSException { //获取MQ连接工厂 ConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD,"tcp://127.0.0.1:61616"); //创建连接 Connection connection = activeMQConnectionFactory.createConnection(); // 启动连接 connection.start(); //创建会话工厂 Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); //创建队列 Queue destination = session.createQueue("sunny_MQ01"); //创建消息生产者 MessageProducer producer = session.createProducer(destination); for (int i = 1; i <=5; i++){ System.out.println("我是消息生产者产出的消息"+i); sendMsg(session,producer,"我是消息生产者产出的消息"+i); } System.out.println("生产者生产消息完毕"); } public static void sendMsg(Session session, MessageProducer producer, String n) throws JMSException { TextMessage ts = session.createTextMessage(n); producer.send(ts); } }2)效果图,执行完生产者应用之后 3. 消费者
1)代码
package com.sunny.producer; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; public class ConsumerTest { public static void main(String[] args) throws JMSException { //获取MQ连接工厂 ConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD,"tcp://127.0.0.1:61616"); //创建连接 Connection connection = activeMQConnectionFactory.createConnection(); // 启动连接 connection.start(); //创建会话工厂 Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); //创建队列 Queue destination = session.createQueue("sunny_MQ01"); //创建消息消费者 MessageConsumer consumer = session.createConsumer(destination); while (true){ TextMessage receive = (TextMessage) consumer.receive(); if (null != receive){ String text = receive.getText(); System.out.println("我是消费者,正在消费"+text); }else{ break; } } System.out.println("消费者消费消息完毕"); } public ConsumerTest() throws JMSException { } }2)效果图,执行完消费者的请求之后
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)