基于Java ActiveMQ的实例讲解
所需引入Jar包:
jms-1.1.jar
activemq-all-5.15.0.jar
生产者
packagecom.mousewheel.demo; importjavax.jms.Connection; importjavax.jms.ConnectionFactory; importjavax.jms.Destination; importjavax.jms.JMSException; importjavax.jms.Message; importjavax.jms.MessageConsumer; importjavax.jms.MessageListener; importjavax.jms.ObjectMessage; importjavax.jms.Session; importorg.apache.activemq.ActiveMQConnectionFactory; publicclassMQConsumerDemo{ publicstaticvoidmain(String[]args)throwsJMSException{ ConnectionFactoryconnectionFactory=newActiveMQConnectionFactory("admin","admin","tcp://192.168.31.33:61616"); Connectionconnection=null; try{ connection=connectionFactory.createConnection(); connection.start(); Sessionsession=connection.createSession(false,Session.AUTO_ACKNOWLEDGE); Destinationdestination=session.createQueue("test-queue"); MessageConsumerconsumer=session.createConsumer(destination); consumer.setMessageListener(newMessageListener(){ @Override publicvoidonMessage(Messagemessage){ try{ MqBeanbean=(MqBean)((ObjectMessage)message).getObject(); System.out.println(bean); if(null!=message){ System.out.println("收到消息"+bean.getName()); } }catch(Exceptione){ //TODO:handleexception } } }); System.out.println("Beginlisten"); }catch(Exceptione){ //TODO:handleexception } } }
消费者
packagecom.mousewheel.demo; importjavax.jms.Connection; importjavax.jms.ConnectionFactory; importjavax.jms.Destination; importjavax.jms.JMSException; importjavax.jms.Message; importjavax.jms.MessageConsumer; importjavax.jms.MessageListener; importjavax.jms.ObjectMessage; importjavax.jms.Session; importorg.apache.activemq.ActiveMQConnectionFactory; publicclassMQConsumerDemo{ publicstaticvoidmain(String[]args)throwsJMSException{ ConnectionFactoryconnectionFactory=newActiveMQConnectionFactory("admin","admin","tcp://192.168.31.33:61616"); Connectionconnection=null; try{ connection=connectionFactory.createConnection(); connection.start(); Sessionsession=connection.createSession(false,Session.AUTO_ACKNOWLEDGE); Destinationdestination=session.createQueue("test-queue"); MessageConsumerconsumer=session.createConsumer(destination); consumer.setMessageListener(newMessageListener(){ @Override publicvoidonMessage(Messagemessage){ try{ MqBeanbean=(MqBean)((ObjectMessage)message).getObject(); System.out.println(bean); if(null!=message){ System.out.println("收到消息"+bean.getName()); } }catch(Exceptione){ //TODO:handleexception } } }); System.out.println("Beginlisten"); }catch(Exceptione){ //TODO:handleexception } } }
以上这篇基于JavaActiveMQ的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。