Example of publishing/subscribing to messages through JMS and example of subscribing to messages through jms

Source: Internet
Author: User

Example of publishing/subscribing to messages through JMS and example of subscribing to messages through jms

Based on the previous article "Tomcat + JNDI + ActiveMQ to implement JMS point-to-point message transmission", you can easily compile a publish/subscribe message transmission example. The environment preparation is similar to this article, the main differences are as follows.

Configure JNDI in Tomcat

Configure the connection factory and topic

    <Resource name="topic/connectionFactory" auth="Container"        type="org.apache.activemq.ActiveMQConnectionFactory" description="JMS Connection Factory"        factory="org.apache.activemq.jndi.JNDIReferenceFactory"        brokerURL="failover:(tcp://localhost:61616)?initialReconnectDelay=100&amp;maxReconnectAttempts=5"        brokerName="LocalActiveMQBroker" useEmbeddedBroker="false" />            <Resource name="topic/topic0"         auth="Container"        type="org.apache.activemq.command.ActiveMQTopic" description="My Topic" factory="org.apache.activemq.jndi.JNDIReferenceFactory"        physicalName="TestTopic" />
Compile code in the Web Factory

Create a publisher Servlet

package pubSub;import java.io.IOException;import java.io.PrintWriter;import javax.naming.InitialContext;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;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;/** * Servlet implementation class JMSTest */@WebServlet("/Publish")public class Publisher extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public Publisher() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        PrintWriter out = response.getWriter();        try {            // get the initial context            InitialContext ctx = new InitialContext();            // lookup the topic object            Topic topic = (Topic) ctx.lookup("java:comp/env/topic/topic0");            // lookup the topic connection factory            TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx                    .lookup("java:comp/env/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            out.write("Message published: " + message.getText());            // close the topic connection            topicConn.close();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub    }}

Create a subscriber Servlet

package pubSub;import java.io.IOException;import java.io.PrintWriter;import javax.jms.Session;import javax.jms.TextMessage;import javax.jms.Topic;import javax.jms.TopicConnection;import javax.jms.TopicConnectionFactory;import javax.jms.TopicSession;import javax.jms.TopicSubscriber;import javax.naming.InitialContext;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class Receive */@WebServlet("/Subscribe")public class Subscriber extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public Subscriber() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        PrintWriter out = response.getWriter();        try {            // get the initial context            InitialContext ctx = new InitialContext();            // lookup the topic object            Topic topic = (Topic) ctx.lookup("java:comp/env/topic/topic0");            // lookup the topic connection factory            TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx                    .lookup("java:comp/env/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            out.write("Message received: " + message.getText());            // close the topic connection            topicConn.close();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub    }}

Run the Web Project, open multiple tags to access the subscription servlet, and then access the published servlet. The result is as follows:

When a subscriber subscribes to a message, the subscriber does not receive the message at first. Once the subscriber publishes the message, the subscriber immediately receives the message.

 

Code reference: http://howtodoinjava.com/jms/jms-publish-subscribe-message-example/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.