Learning JMS (i)--basic instance _JMS

Source: Internet
Author: User
The Java Message Service is one of the specifications of Java EE that can be used to send asynchronous messages, and in some scenarios, can be used as a means of integration between different systems or different modules.

Can be compared to the way to integrate through the database, module A completes the logic, insert a record into the database, module B polling the database, if the corresponding records, the processing. JMS integration is actually the same idea, just more powerful, and provides standard API support, but also can avoid repeatedly polling the database or read the file I/O operations, the overall performance of the system may be improved

The main advantage of this is that 2 systems or modules can be loosely coupled, module A does not need to call module B directly, only to send a treaty-like message to the JMS provider, module B received this message for subsequent business processing

Second, the JMS approach is asynchronous, meaning that module A sends a message and does not need to wait for the response of Module B or the JMS provider, and its business logic can continue

JMS technology corresponds to the specification is jsr914, the implementation of the specification is called JMS provider, common implementations are ACTIVEMQ, JBoss MQ, IBM Websphere MQ, and so on. This paper takes ACTIVEMQ for example

First, ACTIVEMQ use

ActiveMQ (other JMS provider are similar) after installation, the directory structure is this:



Running the Activemq.bat under the Bin directory will start a broker based on the default configuration. Various JMS implementations that seem to have the concept of broker

After startup, it consumes at least 2 ports, and the default is 61616 and 8161.

61616 is waiting for the JMS client connection, and 8161 is a Web application with ACTIVEMQ

Http://localhost:8161/demo, you can see a variety of official examples

Http://localhost:8161/admin, it's ACTIVEMQ's management console.



You can do all sorts of things with queues, such as sending messages, viewing messages, emptying queues, and so on.

ACTIVEMQ can be used in this way even without programming, including my previous company, using WebSphere MQ, and sometimes not programming, to transfer messages directly to and from WebSphere MQ. Of course, most of the cases need to be programmed for JMS client

Ii. Basic concepts of JMS

As mentioned earlier, the implementation of JMS, called the JMS provider, can be considered a JMS server

JMS clients need to be developed by developers, called JMS client

The message mechanism of JMS has 2 kinds of models, one is point to point, which is represented as the form of queue. The message sent, can only be taken away by a receiver

The other is topic, which can be subscribed by multiple subscribers, similar to mass



ConnectionFactory for JMS client to obtain a connection to the JMS provider. Different JMS products, there are different implementations of this interface, such as ACTIVEMQ, the implementation class of this interface is Activemqconnectionfactory

Connection, which is generated by connectionfactory, represents the connection between JMS client and JMS provider

Session, which is generated by connection, represents a conversation. Sessions are key components, message, Producer/consumer, destination are created on the session

Message, this component is very good to understand, is the transmission of messages, including head, properties, the body, which head is required to select

Destination, the source of the message, is where the message is sent to the sender, and where the receiver is getting the message. Destination has 2 sub-interfaces, queue and topic, respectively, corresponding to the 2 models mentioned above

Message Producer, which is the sender, creates the same code for this component:
Java code Destination Dest = Session.createqueue ("Dotaqueue");/message destination MessageProducer producer = Session.crea Teproducer (dest);//Message sender
Notice that you need to take destination as a parameter and pass in the Createproducer () method, which means that the sender of the message is bound to the destination, and the message sent by this sender will be sent to the destination of this binding.

Message Consumer, which is the recipient of messages, is a component that is the opposite of producer

Third, code examples

This is based on ACTIVEMQ for development, so you need to import the jar packages provided by ACTIVEMQ. However, development should be as far as possible for the JMS interface development, not dependent on a specific implementation

The example is run with the main function and does not run in the Java EE container, so there is no way to rely on Jndi to get connectionfactory instances, only to create activemqconnectionfactory manually, So coupled with the implementation of the ACTIVEMQ, there is no way to connect to other JMS implementations. If the actual code, using Jndi or spring, gets the connectionfactory instance, then it can be programmed only for the interface, connected to any JMS provider

For the sake of simplicity, the example does not use spring, and spring actually provides a good support for JMS client, which is described later

The development environment as long as the import Activemq-all-5.6.0.jar can be



It already contains the necessary class for the JMS API, Activemq-core, Javaee-management API, etc.

The first is the example of message producer:
Java code    public class main {          public  static void main (String[] args)  throws JMSException {               String jmsProviderAddress =  "tcp:// localhost:61616 ";//  address                Connectionfactory connectionfactory = new activemqconnectionfactory (                    jmsprovideraddress) ;//  Connectors               connection connection  = connectionfactory.createconnection ();//  Create connection                session session = connection.createsession (false,                     session.auto_acknowledge);//  open session                Destination dest =  Session.createqueue ("Demoqueue");//  message destination                messageproducer producer = session.createproducer (dest);//  message sender               Message message =  Session.createtextmessage ("Hello world");//  message                producer.send (message);//  send                producer.close ();//  close             Session.close ();           connection.close ();          } &nbsP   }  
The code is very simple, you can refer to the above diagram, the components of the relationship is more clear

Then there is the example of message consumer:
Java Code    public static void main (String[] args)  throws jmsexception  {              string jmsprovideraddress  =  "tcp://localhost:61616";//  address                connectionfactory connectionfactory = new activemqconnectionfactory (                     jmsprovideraddress);//  connectors                Connection connection = connectionfactory.createconnection ();//  Create connection                Session session =  Connection.createsession (false,                    session.auto_acknowledgE);//  open session               String  destinationname =  "Demoqueue";               destination dest = session.createqueue (destinationname);//  message destination                MessageConsumer consumer =  Session.createconsumer (dest);               Connection.start ();              Message  Message = consumer.receive ();               TextMessage textMessage =  (textmessage)  message;               string text = textmessage.gettext ();              &NBsp SYSTEM.OUT.PRINTLN ("Retrieve a message from ACTIVEMQ: "  + text);               consumer.close ();            Session.close ();           connection.close ();          }  
And MessageProducer's code is basically similar, the actual implementation of the Javax.jms.MessageListener interface, so there is no need to manually invoke the receive () method

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.