生活随笔
收集整理的這篇文章主要介紹了
深入掌握JMS(五):实战Topic
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
與Queue不同的是,Topic實現(xiàn)的是發(fā)布/訂閱模型,在下面的例子中,啟動2個消費者共同監(jiān)聽一個Topic,然后循環(huán)給這個Topic中發(fā)送多個消息。
view plaincopy to clipboardprint?
import?javax.jms.Connection;??import?javax.jms.JMSException;??import?javax.jms.Message;??import?javax.jms.MessageConsumer;??import?javax.jms.MessageListener;??import?javax.jms.MessageProducer;??import?javax.jms.Session;??import?javax.jms.TextMessage;??import?javax.jms.Topic;??import?org.apache.activemq.ActiveMQConnectionFactory;??import?org.apache.activemq.command.ActiveMQTopic;????public?class?TopicTest?{??????public?static?void?main(String[]?args)?throws?Exception?{??????????ActiveMQConnectionFactory?factory?=?new?ActiveMQConnectionFactory("vm://localhost");???????????????Connection?connection?=?factory.createConnection();??????????connection.start();?????????????????????????????Topic?topic=?new?ActiveMQTopic("testTopic");??????????Session?session?=?connection.createSession(false,?Session.AUTO_ACKNOWLEDGE);??????????????????????????????MessageConsumer?comsumer1?=?session.createConsumer(topic);??????????comsumer1.setMessageListener(new?MessageListener(){??????????????public?void?onMessage(Message?m)?{??????????????????try?{??????????????????????System.out.println("Consumer1?get?"?+?((TextMessage)m).getText());??????????????????}?catch?(JMSException?e)?{??????????????????????e.printStackTrace();??????????????????}??????????????}??????????});?????????????????????????????MessageConsumer?comsumer2?=?session.createConsumer(topic);??????????comsumer2.setMessageListener(new?MessageListener(){??????????????public?void?onMessage(Message?m)?{??????????????????try?{??????????????????????System.out.println("Consumer2?get?"?+?((TextMessage)m).getText());??????????????????}?catch?(JMSException?e)?{??????????????????????e.printStackTrace();??????????????????}??????????????}???????????????????????});?????????????????????????????MessageProducer?producer?=?session.createProducer(topic);??????????for(int?i=0;?i<10;?i++){??????????????producer.send(session.createTextMessage("Message:"?+?i));??????????}??????}??}??
運行后得到下面的輸出結(jié)果:
view plaincopy to clipboardprint?
Consumer1?get?Message:0??Consumer2?get?Message:0??Consumer1?get?Message:1??Consumer2?get?Message:1??Consumer1?get?Message:2??Consumer2?get?Message:2??Consumer1?get?Message:3??Consumer2?get?Message:3??Consumer1?get?Message:4??Consumer2?get?Message:4??Consumer1?get?Message:5??Consumer2?get?Message:5??Consumer1?get?Message:6??Consumer2?get?Message:6??Consumer1?get?Message:7??Consumer2?get?Message:7??Consumer1?get?Message:8??Consumer2?get?Message:8??Consumer1?get?Message:9??Consumer2?get?Message:9??
說明每一個消息都會被所有的消費者消費。
總結(jié)
以上是生活随笔為你收集整理的深入掌握JMS(五):实战Topic的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。