基于Java ActiveMQ的实例讲解
程序员文章站
2024-02-28 11:54:10
所需引入jar包:
jms-1.1.jar
activemq-all-5.15.0.jar
生产者
package com.mousewheel.demo;...
所需引入jar包:
jms-1.1.jar
activemq-all-5.15.0.jar
生产者
package com.mousewheel.demo; import javax.jms.connection; import javax.jms.connectionfactory; import javax.jms.destination; import javax.jms.jmsexception; import javax.jms.message; import javax.jms.messageconsumer; import javax.jms.messagelistener; import javax.jms.objectmessage; import javax.jms.session; import org.apache.activemq.activemqconnectionfactory; public class mqconsumerdemo { public static void main(string[] args) throws jmsexception { connectionfactory connectionfactory = new activemqconnectionfactory("admin", "admin", "tcp://192.168.31.33:61616"); connection connection = null; try { connection = connectionfactory.createconnection(); connection.start(); session session = connection.createsession(false, session.auto_acknowledge); destination destination = session.createqueue("test-queue"); messageconsumer consumer = session.createconsumer(destination); consumer.setmessagelistener(new messagelistener() { @override public void onmessage(message message) { try { mqbean bean = (mqbean) ((objectmessage) message).getobject(); system.out.println(bean); if (null != message) { system.out.println("收到消息" + bean.getname()); } } catch (exception e) { // todo: handle exception } } }); system.out.println("begin listen"); } catch (exception e) { // todo: handle exception } } }
消费者
package com.mousewheel.demo; import javax.jms.connection; import javax.jms.connectionfactory; import javax.jms.destination; import javax.jms.jmsexception; import javax.jms.message; import javax.jms.messageconsumer; import javax.jms.messagelistener; import javax.jms.objectmessage; import javax.jms.session; import org.apache.activemq.activemqconnectionfactory; public class mqconsumerdemo { public static void main(string[] args) throws jmsexception { connectionfactory connectionfactory = new activemqconnectionfactory("admin", "admin", "tcp://192.168.31.33:61616"); connection connection = null; try { connection = connectionfactory.createconnection(); connection.start(); session session = connection.createsession(false, session.auto_acknowledge); destination destination = session.createqueue("test-queue"); messageconsumer consumer = session.createconsumer(destination); consumer.setmessagelistener(new messagelistener() { @override public void onmessage(message message) { try { mqbean bean = (mqbean) ((objectmessage) message).getobject(); system.out.println(bean); if (null != message) { system.out.println("收到消息" + bean.getname()); } } catch (exception e) { // todo: handle exception } } }); system.out.println("begin listen"); } catch (exception e) { // todo: handle exception } } }
以上这篇基于java activemq的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。