java——activemq 偏执的太偏执、 2022-04-24 01:46 154阅读 0赞 参考原博文[https://www.cnblogs.com/parryyang/p/6062160.html][https_www.cnblogs.com_parryyang_p_6062160.html] 消息发布: public static final String MQ_NAME = ""; public static final String MQ_PASSWORD = ""; //public static final String MQ_BROKETURL = ""; public static final String MQ_BROKETURL = "failover:(tcp://192.168.0.1:61616?wireFormat.maxInactivityDuration=0)&maxReconnectDelay=1000"; public static final String QUEUE=""; public static void publish(String content) { ConnectionFactory factory; Connection connection = null; Session session; Destination destination; MessageProducer messageProducer; try { factory = new ActiveMQConnectionFactory(MQ_NAME,MQ_PASSWORD,MQ_BROKETURL); connection = factory.createConnection(); connection.start(); session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(QUEUE); messageProducer = session.createProducer(destination); // messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); TextMessage message = session.createTextMessage(content); messageProducer.send(message); session.commit(); } catch (JMSException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } } 消息订阅: public class Consumer { public static final String MQ_NAME = ""; public static final String MQ_PASSWORD = ""; public static final String MQ_BROKETURL = ""; public static final String QUEUE=""; public static void main(String[] args) throws Exception { ConnectionFactory connectionFactory; Connection connection = null; Session session; Destination destination; try { connectionFactory = new ActiveMQConnectionFactory(MQ_NAME,MQ_PASSWORD,MQ_BROKETURL); connection = connectionFactory.createConnection(); connection.start(); // 创建接收或发送的线程实例(消费者就不需要开启事务了) session = connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(QUEUE); MessageConsumer consumer = session.createConsumer(destination); while(true) { consumer.setMessageListener(new MQListerner()); } } catch (JMSException e) { e.printStackTrace(); } } } public class MQListerner implements MessageListener{ @Override public void onMessage(Message message) { try { System.out.println(((TextMessage)message).getText()); } catch (JMSException e) { e.printStackTrace(); } } } [https_www.cnblogs.com_parryyang_p_6062160.html]: https://www.cnblogs.com/parryyang/p/6062160.html
还没有评论,来说两句吧...