Introduction to JMS

Source: Internet
Author: User

JMS (Java Message Service). Used to pass a message between application.

Enterprise Message

WebSphere MQ, SONICMQ, Microsoft message Queue (MSMQ), ActiveMQ, Message Bean in EJB, ESB in SOA (Enterprise message Bus) and so on are enterprise Message.

When you use enterprise message, you have the following options:

Centralized type

Distributed

Mixed type

A daemon program is installed on each client, the client and daemon use TCP communication, and multicast is used between daemon and other daemon.

JMS Message Model

JMS supports two message models: Point-to-Point, publish-and-subscribe.

Point-to-Point

A JMS client can send and receive messages to (from) a queue in the peer model. It can be either synchronous or asynchronous. The message is obtained by pulling (pull). Sender is called sender, receiver is called receiver.

Publish-and-subscribe

Messages are sent in push mode. Even if the subscriber is offline, it will be sent. The sender is called publisher, and the receiver is called Subscriber.

JMS API Brief

JMS only defines the interface, and there is no specific implementation, the implementation is done by the relevant vendors. This is similar to JDBC.

The JMS API can be divided into 3 main parts: 1) Generic API, 2) peer-to api,3) Pub/sub API.

Several of the main interfaces are:

· ConnectionFactory

· Destination

· Connection

· Session

· Message

· MessageProducer

· Messageconsumer

In the above interface, ConnectionFactory, destination must be obtained through JNDI, in fact, the interface is based on these two to create. After getting connectionfactory, you can get connection; With connection you can create a session, and with the session, you can create a message, MessageProducer, Messageconsumer.

The creation of the instance is as follows:

In JMS, the session object holds transactional, not connection, which is not the same as JDBC. That is, when using JMS, an app will only create a connection object that can create multiple session objects based on the Connection object.

Point-to-Point

This is an interface designed for peer-to-peer. Corresponds to universal interface one by one.

Publish/subscribe

Similarly, the interface has been specifically designed for Pub/sub:

JMS Pub/sub Example

To run JMS, you need a JMS proxy server. In the following example, ACTIVEMQ is used as a proxy server.

After the installation is complete ACTIVEMQ, start it.

The sample program is a simple chat room.

 PackageCom.fjn.java.jms.topic;Importjava.io.IOException;Importjava.util.Properties;ImportJava.util.Scanner;Importjavax.jms.JMSException;ImportJavax.jms.Message;ImportJavax.jms.MessageListener;Importjavax.jms.Session;ImportJavax.jms.TextMessage;ImportJavax.jms.Topic;Importjavax.jms.TopicConnection;Importjavax.jms.TopicConnectionFactory;ImportJavax.jms.TopicPublisher;Importjavax.jms.TopicSession;ImportJavax.jms.TopicSubscriber;ImportJavax.naming.InitialContext;Importjavax.naming.NamingException; Public classChatImplementsMessageListener {Privatetopicsession pubsession; PrivateTopicpublisher Publisher; Privatetopicconnection Connection; PrivateString username;  PublicChat (String Factoryjdni, String topicname, string username)throwsnamingexception, JMSException, IOException {Properties props=NewProperties (); Props.load (Chat.class. getResourceAsStream ("Jndi.properties")); InitialContext CTX=NewInitialContext (props); Topicconnectionfactory connfactory=(topicconnectionfactory) ctx. Lookup (FACTORYJDNI); Topic Topic=(Topic) ctx.lookup (topicname); Topicconnection Conn=connfactory.createtopicconnection (); Topicsession pubsession= Conn.createtopicsession (false, Session.auto_acknowledge); Topicsession subsession= Conn.createtopicsession (false, Session.auto_acknowledge); Topicpublisher Publisher=pubsession.createpublisher (topic); TopicSubscriber Subscriber= Subsession.createsubscriber (Topic,NULL,                true); Subscriber.setmessagelistener ( This);  This. Connection =Conn;  This. Publisher =publisher;  This. pubsession =pubsession;  This. Username =username;    Conn.start (); } @Override Public voidonMessage (Message msg) {Try{textmessage text=(TextMessage) msg;        System.out.println (Text.gettext ()); } Catch(jmsexception e) {e.printstacktrace (); }    }    protected voidWritemessage (String text)throwsjmsexception{textmessage msg=Pubsession.createtextmessage (); Msg.settext (username+": "+text);    Publisher.publish (msg); }         Public voidClose ()throwsjmsexception{connection.close (); }         Public Static voidMain (string[] args)throwsnamingexception, jmsexception, IOException {chat chat=NewChat ("TOPICCF", "Topic1", "Zhangsan"); Scanner Scanner=NewScanner (system.in);  while(true) {String line=Scanner.nextline (); if("Exit". Equals (line))                {Chat.close (); System.exit (0);            Scanner.close (); }Else{chat.writemessage (line); }        }    }} PackageCom.fjn.java.jms.topic;Importjava.io.IOException;ImportJava.util.Scanner;Importjavax.jms.JMSException;Importjavax.naming.NamingException; Public classCHAT2 { Public Static voidMain (string[] args)throwsnamingexception, jmsexception, IOException {chat chat=NewChat ("TOPICCF", "Topic1", "LiSi"); Scanner Scanner=NewScanner (system.in);  while(true) {String line=Scanner.nextline (); if("Exit". Equals (line))                {Chat.close (); System.exit (0);            Scanner.close (); }Else{chat.writemessage (line); }        }    }}

In fact, you can make a slight change to the main method of the program, so that the three parameters for creating chat are obtained from the named line. In this way, you can start any client.

Jndi.properties File Contents:

java.naming.factory.initial = Org.apache.activemq.jndi.ActiveMQInitialContextFactoryjava.naming.provider.url = TCP ://localhost:61616java.naming.security.principal=systemjava.naming.security.credentials= Managerconnectionfactorynames = Topiccftopic.topic1 = Jms.topic1


This makes it possible to have multiple client conversations, that is, group conversations.

Introduction to JMS

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.