[ActiveMQ actual combat] pub/sub communication mechanism based on JMS _ACTIVEMQ

Source: Internet
Author: User
Tags message queue

The last blog introduced the ACTIVEMQ based on JMS point-to-point messaging mechanism implementation, here is another publish/subscribe method implementation.

Publish subscription model

It's like subscribing to a newspaper. We can choose one or more newspapers, for example: Beijing daily, People's daily. These newspapers are equivalent to topic in the release subscription model. If a lot of people subscribe to the same newspaper, we are registered in the same topic, and for the newspaper publisher, it has a one-to-many relationship with all the subscribers. As follows:


Ii. implementation of the publisher

Package com.tgb.activemqTopic;

Import Java.awt.font.TextMeasurer;
Import javax.jms.Connection;
Import Javax.jms.ConnectionFactory;
Import javax.jms.Destination;
Import javax.jms.JMSException;
Import Javax.jms.MessageProducer;
Import javax.jms.Session;

Import Javax.jms.TextMessage;
Import org.apache.activemq.ActiveMQConnection;

Import Org.apache.activemq.ActiveMQConnectionFactory; /** * Message Publisher * @author XX */public class Jmsproducer {//default connection username private static final String USERNAME = Activemqco Nnection.
	Default_user;
	Default connection password private static final String PASSWORD = Activemqconnection.default_password;
	Default connection address private static final String Brokeurl = Activemqconnection.default_broker_url;
	
	Number of messages sent private static final int sennum = 10; public static void Main (string[] args) {ConnectionFactory factory;//connection factory Connection Connection = null;//Connection Sessi on session; session, the thread that receives or sends the message destination destination; The destination of the message MessageProducer messageproducer; Message producer//instantiationConnection Factory factory = new Activemqconnectionfactory (Jmsproducer.username, Jmsproducer.password, Jmsproducer.brokeurl);
			Get connection try {connection = Factory.createconnection () from the connection factory; Connection.start ();
			Initiate connection//create Session session = Connection.createsession (Boolean.true, Session.auto_acknowledge);
			
			Create message queue//destination = Session.createqueue ("Firstqueue");
			Create a theme Destination = Session.createtopic ("Topic1");
			Create a message Publisher MessageProducer = Session.createproducer (destination);
			Send Message SendMessage (session, MessageProducer);
		Session.commit ();
		catch (JMSException e) {e.printstacktrace ();
				}finally{if (connection!= null) {try {connection.close ();
				catch (JMSException e) {e.printstacktrace (); /** * Send Message * @param session * @param MP * @throws jmsexception/public static void Sendmess Age (Sessions session, MessageProducer MP) throws jmsexception{for (int i = 0;i<jmsproducer.sennum;i+ +) {TextMessage message = Session.createtextmessage ("ActiveMq released messages" + i);
			System.out.println ("Post message:" + "ActiveMq released message" + i);
		Mp.send (message);
 }
	}
}

The difference between this and the point-to-point is that it is no longer about creating a message queue, but creating a topic. And it is not the message producer but the publisher.

Third, Subscribers

There are more than one subscribers, all of them listening to the same topic. Here to build at least two subscribers for the test effect, I only write one here, and the other people write on the line.

1. Subscribers '

Package com.tgb.activemqTopic;
Import javax.jms.Connection;
Import Javax.jms.ConnectionFactory;
Import javax.jms.Destination;
Import Javax.jms.MessageConsumer;
Import javax.jms.Session;

Import Javax.jms.TextMessage;
Import org.apache.activemq.ActiveMQConnection;

Import Org.apache.activemq.ActiveMQConnectionFactory; /** * Message Subscriber A * @author XX/public class JMSConsumer1 {///default connection username private static final String USERNAME = ACTIVEMQC Onnection.
	Default_user;
	Default connection password private static final String PASSWORD = Activemqconnection.default_password;
	
	Default connection address private static final String Brokeurl = Activemqconnection.default_broker_url; public static void Main (string[] args) {ConnectionFactory factory;//connection factory Connection Connection = null;//Connection Sess Ion session; session, the thread that receives or sends the message destination destination; The destination of the message Messageconsumer Messageconsumer; Message Consumer//instantiated connection Factory factory = new Activemqconnectionfactory (Jmsconsumer1.username, Jmsconsumer1.password, JMSConsumer1. Brokeurl);
			Get connection try {connection = Factory.createconnection () from the connection factory; Connection.start ();
			Initiate connection//create Session session = Connection.createsession (Boolean.false, Session.auto_acknowledge);
			Create a connection message queue where the message arrives at the destination//Destination = Session.createqueue ("Firstqueue");
			Destination = Session.createtopic ("Topic1");
			Create Consumer Messageconsumer = Session.createconsumer (destination);
		Register Message Listener Messageconsumer.setmessagelistener (new Listener1 ());
		}catch (Exception e) {e.printstacktrace ();
 }
	}
}


2. Listening class

Package com.tgb.activemqTopic;

Import javax.jms.JMSException;
Import Javax.jms.Message;
Import Javax.jms.MessageListener;
Import Javax.jms.TextMessage;

/**
 * Subscriber 1 Monitor
 * Message Listener class
 * @author XX */
 public
class Listener1 implements MessageListener {

	@ Override public
	void OnMessage {
		try {
			System.out.println ("The Subscriber receives a message:" + ( textmessage) message). GetText ());
		catch (JMSException e) {
			e.printstacktrace ();}}}



Four, test

Like point to point to start the producer, the producer wants to produce the message. To publish the subscription model, start the Subscriber first, subscribe to the topic, and then publish the message.

1. Start Subscriber, here I start two, can see in topic registered two consumer


2. Launch the publisher as follows

The publisher released 10 data, but there were 20 out of the team because there were two subscribers.

V. Summary

The publisher publishes a message to a specific message subject, and 0 or more subscribers may be interested in receiving messages from a specific message topic. Where publishers and Subscribers do not know each other's presence.



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.