Jms basics (II)

Source: Internet
Author: User
Introduction

Heterogeneous integration is a field in which messages play a role. Large Companies may encounter many internal platforms, such as Java,. net, or their own platforms.

Message transmission should also support asynchronous mechanisms to improve the overall system performance. Asynchronous transmission of a message means that the sender does not have to wait for the receiver to receive or process the message, but can proceed with subsequent processing.

When an application sends a message to another application, it must use message-oriented middleware. Message-oriented middleware should provide fault tolerance, load balancing, and scalable transactional features.

Similar to JDBC, JMS is a vendor-independent API. Application developers can use the same API to access different systems.

It can be considered that JMS is a standard, and various message middleware (MOM) is the specific implementation of JMS. Common moms include WebSphere MQ, sonic MQ, and activemq.

JMS system organization

Message transmission systems can be divided into centralized and distributed systems.

A centralized message system depends on a message server, or a message router or broker, to receive and distribute messages.

The most common structure of a centralized message system is the star structure.

 

Figure 1 Structure of a centralized message system

The distributed message system is based on IP multicast. The entire structure can be divided into Multiple Multicast Groups. Each multicast group uses one IP address, and the client can join one or more multicast groups. Message transmission does not depend on the message server and is handled by the network itself.

 

Figure 2 distributed Message System Structure

There are two types of message transmission models: point-to-point and publish/subscribe.

 

Figure 3 message transmission model

The client that produces messages becomes the producer, and the client that consumes messages becomes the consumer. A jms client can be both a producer and a consumer.

The point-to-point model is based on pulling (pull) or polling (polling). Consumers can retrieve messages from the queue. Publishing/subscription is based on push. messages are actively pushed from producers to consumers.

A simple example

Use JMS to write a simple chat program. The Code is as follows:   

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import javax. JMS. jmsexception; import javax. JMS. message; import javax. JMS. messagelistener; import javax. JMS. textmessage; import javax. JMS. topic; import javax. JMS. topicconnection; import javax. JMS. topicconnectionfactory; import javax. JMS. topicpublisher; import javax. JMS. topicsession; import javax. JMS. topicsubscriber; imp ORT javax. naming. context; import javax. naming. namingexception; import JMS. listener; public class chat implements messagelistener {private topicpublisher publisher; private topicsubscriber subscriber; private topicsession pubsession = NULL, subsession = NULL; private topicconnection connection = NULL; public chat () throws jmsexception, interruptedexception, namingexception {topicconnectionfactory Factory = NULL; Context CTX = NULL; try {jndifactoryforjms factoryforjms = new jndifactoryforjms (); CTX = factoryforjms. getjndicontext (); // obtain the connection factory. Factory = (topicconnectionfactory) CTX. lookup ("con1");} catch (namingexception e) {e. printstacktrace ();} // create a connection = factory. createtopicconnection (); // create sessionpubsession = connection. createtopicsession (false, pubsession. auto_acknowledge); subsession = connection. createtopicsession (false, pubsession. auto_acknowledge); // specify the topic = (topic) CTX in the message queue. lookup ("mytopic"); Publisher = pubsession. createpublisher (topic); subscriber = pubsession. createsubscriber (topic, null, true); subscriber. setmessagelistener (this); // establish a connection. start ();} public static void main (string [] SRGs) throws jmsexception, interruptedexception, namingexception, ioexception, clonenotsupportedexception {chat = new chat (); bufferedreader CommandLine = new bufferedreader (New inputstreamreader (system. in); While (true) {string S = CommandLine. readline (); If (S. equalsignorecase ("exit") {chat. close (); system. exit (-1);} else {chat. writemessage (s) ;}}@ overridepublic void onmessage (message) {textmessage MEs = (textmessage) message; try {system. out. println (mes. gettext ();} catch (jmsexception e) {e. printstacktrace () ;}} private void writemessage (string text) throws jmsexception {textmessage MEs = pubsession. createtextmessage (text); Publisher. publish (MES);} private void close () throws jmsexception {connection. close ();}}

  

Start the program in multiple copies and enter information in the console window of any program. You can see that the entered content appears in the console window of another program, it indicates that another program has received the message and printed the message content.

Analyze the above JMS-based chat program:

The above JMS chat program is based on JNDI and does not use the JNDI server. Therefore, a configuration file is required, and the above class must be placed in the same level directory.

Java. Naming. Factory. Initial = org. Apache. activemq. JNDI. activemqinitialcontextfactory

Java. Naming. provider. url = TCP: // localhost: 61616

Java. Naming. Security. Principal = System

Java. Naming. Security. Credentials = Manager

Connectionfactorynames = con1, con2

# Queue. myqueue = myqueue

Topic. mytopic = mytopic

Topic. topic1 = JMS. topic1

Jndifactoryforjms is a factory class that initializes the JNDI environment. The Code is as follows:

import java.util.Properties;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;public class JndiFactoryForJMS { protected Context context = null;            public void initalize() throws NamingException      {                 Properties props = new Properties();          try{          org.apache.activemq.jndi.ActiveMQInitialContextFactory af = new org.apache.activemq.jndi.ActiveMQInitialContextFactory();            props.load(this.getClass().getResourceAsStream("jndi.properties"));            context = new InitialContext(props);          }catch(Exception ex){          ex.printStackTrace();        }                    }        public Context getJndiContext() throws NamingException {          if(context == null){              initalize();          }          return context;      }       }  

  

The JNDI-related section in the analysis code:

Jndifactoryforjms factoryforjms =NewJndifactoryforjms ();

CTX = factoryforjms. getjndicontext ();

// Obtain the connection factory.

Factory = (topicconnectionfactory) CTX. Lookup ("con1 ");

 

  

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.