在JMS 教程 中,您了解了 JMS 消息传递域点对点域和发布订阅域。在本例中,我们将通过一个这样的发布/订阅消息域示例。发布/订阅消息传递域是一种一对多模型,其中一个发布者通过 topic
将消息发送给所有活跃的订阅者,他们收到通过主题的消息。
下面给出了发送方应用程序的典型发布/订阅消息传递示例。应用程序的以下步骤是 -
让我们看下面的例子:
package pubSub; import javax.naming.InitialContext; import javax.jms.Topic; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.TopicPublisher; import javax.jms.DeliveryMode; import javax.jms.TopicSession; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; public class Publisher { public static void main(String[] args) throws Exception { // get the initial context InitialContext ctx = new InitialContext(); // lookup the topic object Topic topic = (Topic) ctx.lookup("topic/topic0"); // lookup the topic connection factory TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx. lookup("topic/connectionFactory"); // create a topic connection TopicConnection topicConn = connFactory.createTopicConnection(); // create a topic session TopicSession topicSession = topicConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // create a topic publisher TopicPublisher topicPublisher = topicSession.createPublisher(topic); topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // create the "Hello World" message TextMessage message = topicSession.createTextMessage(); message.setText("Hello World"); // publish the messages topicPublisher.publish(message); // print what we did System.out.println("Message published: " + message.getText()); // close the topic connection topicConn.close(); } }
接收方的大部分步骤与发送方应用程序相同 - 除了它将侦听消息而不是发送 JMS 消息。
package pubSub; import javax.naming.InitialContext; import javax.jms.Topic; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; public class Subscriber { public static void main(String[] args) throws Exception { // get the initial context InitialContext ctx = new InitialContext(); // lookup the topic object Topic topic = (Topic) ctx.lookup("topic/topic0"); // lookup the topic connection factory TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx. lookup("topic/connectionFactory"); // create a topic connection TopicConnection topicConn = connFactory.createTopicConnection(); // create a topic session TopicSession topicSession = topicConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // create a topic subscriber TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); // start the connection topicConn.start(); // receive the message TextMessage message = (TextMessage) topicSubscriber.receive(); // print the message System.out.println("Message received: " + message.getText()); // close the topic connection topicConn.close(); } }
在上面的代码中,接收方将从发送方接收消息并将其打印出来,即 Hello World。
快乐学习!!
标签2: JMS地址:https://www.cundage.com/article/jms-publish-subscribe-message-example.html