ActiveMQ接收消息
之前写了一个ActiveMQ发送消息的例子。现在记录一下java接收ActiveMQ消息的代码。
package com.syxp.dns.receive; import javax.jms.Connection; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.log4j.Logger; public class ReceiveMessageFromMQ { private static String url = "tcp://localhost:61616"; private static String user = ""; private static String password = ""; private static Logger logger = Logger.getLogger(ReceiveMessageFromMQ.class); public void receiveMessage(){ // 创建连接工厂 ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); // 创建连接 Connection connection; try { connection = connectionFactory.createConnection(); connection.start(); // 创建Session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 创建目标,就创建主题也可以创建队列 Destination destination = session.createQueue("integratedalarm.subject"); // 创建消息消费者 MessageConsumer consumer = session.createConsumer(destination); // 接收消息,参数:接收消息的超时时间,为0的话则不超时,receive返回下一个消息,但是超时了或者消费者被关闭,返回null Message message = consumer.receive(1000); if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); logger.info("接收的消息:"+"\n"+text); } else { logger.info("接收的消息:"+"\n"+message); } consumer.close(); session.close(); connection.close(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { ReceiveMessageFromMQ receiveMessageFromMQ = new ReceiveMessageFromMQ(); receiveMessageFromMQ.receiveMessage(); } }
上面有详细的注释,运行了上面的接收的方法之后,会打印出一条相应队列的未接收消息。在ActiveMQ的监视控制页面中,可以看到有一条消息已经被消费。
相关推荐
胡献根 2020-07-18
胡献根 2020-07-05
jiangtie 2020-06-10
onlylixiaobei 2020-06-09
xinglun 2020-06-02
方新德 2020-05-31
Java高知 2020-05-20
Java高知 2020-05-08
Java高知 2020-05-03
onlylixiaobei 2020-05-02
Java高知 2020-04-22
胡献根 2020-04-22
heweiyabeijing 2020-04-21
方新德 2020-04-20
胡献根 2020-04-10
onlylixiaobei 2020-04-10
方新德 2020-04-08
xuedabao 2020-03-30