Spring consolidated JMS for network communication __spring Consolidated JMS for network communication

Source: Internet
Author: User
Tags getmessage throwable dreamforce
what is JMS.

The JMS-the Java Message Service-application interface is a Java platform-oriented messaging middleware (MOM) API for sending messages and communicating asynchronously between two applications, or distributed systems. The Java Messaging Service is a platform-independent API, with most MOM providers supporting JMS. the advantages of JMS

At present, CORBA, DCOM, RMI and other RPC middleware technologies have been widely used in various fields. But in the face of distributed systems with increasing scale and complexity, these technologies also show their limitations:

(1) Synchronous communication: After the client makes the call, it must wait for the service object to finish processing and return the result before it can continue execution;

(2) The life cycle of customers and service objects is tightly coupled: both the client process and the service object process must function properly; If the client's request is not reached due to a crash of the service object or a network failure, the customer receives an exception;

(3) Point-to-Point communication: A call from a customer is sent only to a single target object.
Message-oriented middleware (oriented Middleware,mom) solves the above problems better. The sender sends the message to the message server, which stores the message in several queues and forwards the message to the recipient at the appropriate time. In this mode, sending and receiving are asynchronous, the sender does not have to wait; the life cycle of the two is not necessarily the same: the receiver does not necessarily run when the message is sent, and the sender does not necessarily run when the message is received; One-to-many communication: There can be multiple receivers for a message.
Existing MOM systems include IBM's MQSeries, Microsoft's MSMQ, and Bea's Messageq. Without a common standard, it is difficult for these systems to interoperate and connect seamlessly.

The Java message Service (JMS) is the specification that Sun proposes to unify the various MOM system interfaces, which includes point-to-point to POINT,PTP and publish/subscribe (PUBLISH/SUBSCRIBE,PUB/SUB) Two messaging models , providing reliable message transmission, transaction and message filtering mechanisms. JMS is not a product but a specification, and the advent of JMS is a huge change.

Meet the needs of a large number of applications, running on a variety of hardware and operating system platforms, support distributed computing, support standard interfaces and protocols. By invoking a large number of APIs provided by the middleware, developers can realize the communication of heterogeneous environments, thus shielding the complex operating system and network protocols in heterogeneous systems.

Because of the importance of standard interfaces for portability and standard protocols for interoperability, middleware has become a major part of many standardization efforts. Distributed application software can share resources among different technologies with the help of middleware.

In general, middleware masks the complexity of the underlying operating system, allows program developers to face a simple and unified development environment, reduce the complexity of programming, focus on their own business, do not have to the program on different software systems for the porting and duplication of work, thereby greatly reducing the technical burden.

Take in Action

After understanding what JMS is, in practice, Dreamforce will introduce you to consolidating JMS in spring while combining Apache ACTIVEMQ to implement an analog chat function.

Incoming scene: A on the input side of the message, the message will be sent asynchronously to the activemq,b side will listen to this queue, if there is new data queued, then receive this message.

According to this example, you can realize the free chat function of two or more people by simple modification.

In this example, the use of Apache ACTIVEMQ as a JMS middleware, this is a fairly mature and open source products, has been many people in the industry praise.

Develop a SPIRNG MAVEN integrated development environment where all jar packages are managed through MAVEN, and if you are unfamiliar with the spring MAVEN integrated development environment, look here first: http://dreamforce.me/archives/87

Create a new Applicationcontext-jms.xml

Define JMS Connection factory Java code <bean id= "Jmsfactory" class= "Org.apache.activemq.ActiveMQConnectionFactory" > <property Name= "Brokerurl" value= "tcp://localhost:61616"/> </bean>

<bean id= "Jmsfactory" class= "org.apache.activemq.ActiveMQConnectionFactory" >        
 <property name= " Brokerurl "value=" tcp://localhost:61616 "/>     </bean> 

Define JMS Template Java code <bean id= "Jmstemplate" class= "Org.springframework.jms.core.JmsTemplate" > <property Name= "ConnectionFactory" ref= "Jmsfactory"/> </bean>

<bean id= "Jmstemplate" class= "org.springframework.jms.core.JmsTemplate" >         
<property name= " ConnectionFactory "ref=" jmsfactory "/>     </bean> 
Define message Destinations Java code <bean id= "Dreamdestination" class= "Org.apache.activemq.command.ActiveMQQueue" > < Constructor-arg index= "0" value= "Dream.force"/> </bean>
<bean id= "dreamdestination" class= "Org.apache.activemq.command.ActiveMQQueue" >         <constructor-arg index= "0" value= "dream.force"/>     </bean> 
Define receive listener Java code <bean id= "Mytextlistener" class= "Com.darcy.jms.TextListener" > </bean>
<bean id= "Mytextlistener" class= "Com.darcy.jms.TextListener" >     
</bean> 

Define a JMS topic Java code <bean id= "Jmstopic" class= "Org.apache.activemq.command.ActiveMQTopic" autowire= "constructor" > <constructor-arg value= "STOCKS. Dreamforce.jms "/> </bean>

<bean id= "Jmstopic" class= "Org.apache.activemq.command.ActiveMQTopic" autowire= "constructor"
        > 
        < Constructor-arg value= "STOCKS. Dreamforce.jms "/> 
    </bean>

Define consumer (Receive-side) Java code <bean id= "Javaconsumer" class= " Org.springframework.jms.listener.DefaultMessageListenerContainer "> <property name=" connectionfactory "ref=" Jmsfactory "/> <property name=" destination "ref=" chartdestination "/> <property name=" MessageListener "ref = "Mytextlistener"/> </bean>

<bean id= "Javaconsumer"
        class= "Org.springframework.jms.listener.DefaultMessageListenerContainer" > 
        <property name= "ConnectionFactory" ref= "jmsfactory"/> <property name= "Destination" 
        Chartdestination "/> <property name= messagelistener" ref= "Mytextlistener"/> 
    </bean> 

Define publisher Java code <bean id= "publisher" class= "Com.darcy.jms.SpringPublish" > <property name= "template" > <ref Local= "Jmstemplate"/> </property> <property name= "destinations" ref= "Chartdestination"/> </bean >

<bean id= "publisher" class= "Com.darcy.jms.SpringPublish" >        
 <property name= "template" >            
 <ref Local= "Jmstemplate"/>         
</property> <property name= "destinations" ref=         
"Chartdestination"/>     
</bean> 

The Java core code typically consists of three parts: a listener (Listener), a publisher (publisher), and a message producer (Creator)

Listener: Java code package COM.DARCY.JMS; Import Java.util.Date; Import javax.jms.JMSException; Import Javax.jms.Message; Import Javax.jms.MessageListener; Import Javax.jms.TextMessage; Import Org.apache.activemq.command.ActiveMQMapMessage; public class TextListener implements messagelistener{public void onMessage (Message message) {activemqmapmessage msg = Nu ll System.out.println ("ONMessage-----------------" +message.tostring ()); try {if (instanceof activemqmapmessage) {msg = (activemqmapmessage) message; String sentdate = msg.getstring ("date"); String remessage = msg.getstring ("message"); int sentcount = Msg.getint ("Count"); System.out.println ("-------------New message arrival-----------" +new Date ()); System.out.println ("It" +sentcount+ "Time from Darcy:" +remessage+ "---Send time:" + sentdate);} catch (JMSException e) {System.out.println ("jmsexception in OnMessage ():" + e.tostring ());} catch (Throwable t) {System.out.println ("Exception in OnMessage ():" + t.getmessage ());} } }

Package COM.DARCY.JMS; 
Import Java.util.Date;
Import javax.jms.JMSException; 
Import Javax.jms.Message; 
Import Javax.jms.MessageListener; 
Import Javax.jms.TextMessage;  

Import Org.apache.activemq.command.ActiveMQMapMessage; public class TextListener implements messagelistener{public void onMessage (Message message) {Active         
	Mqmapmessage msg = NULL;         

	System.out.println ("ONMessage-----------------" +message.tostring ());                  
			try {if (instanceof activemqmapmessage) {msg = (activemqmapmessage) message;                 
			String sentdate = msg.getstring ("date");                 
			String remessage = msg.getstring ("message");                 
			int sentcount = Msg.getint ("Count"); 
			System.out.println ("-------------New message arrival-----------" +new Date ());             
		System.out.println ("It S" +sentcount+ "time from Darcy:" +remessage+ "---Send time:" + sentdate);     }    
	catch (JMSException e) {System.out.println ("jmsexception in OnMessage ():" + e.tostring ());         
	catch (Throwable t) {System.out.println ("Exception in OnMessage ():" + t.getmessage ()); 
 }     
   }   
}

Publishing End: Java code package COM.DARCY.JMS; Import Java.util.HashMap; Import Java.util.Scanner; Import javax.jms.Destination; Import Org.springframework.jms.core.JmsTemplate; public class Springpublish {private jmstemplate template; private destination[] Destinations: public void chart () {Boolea n chart = true; int count = 0; while (chart) {count + +; Scanner cin=new Scanner (system.in); SYSTEM.OUT.PRINTLN ("Input chat content, input n stop chatting"); String Text=cin.nextline (); if (Text.equals ("N")) {chart = false;} System.out.println ("I:" +text); Sendchartmessage (Count,text); }} protected void Sendchartmessage (int count, String strmessage) {Mymessagecreator creator = new Mymessagecreator (count , strmessage); Template.send (Destinations[0], creator); Public Jmstemplate GetTemplate () {return template.} public void SetTemplate (jmstemplate template) {this.template = Te Mplate; Public destination[] Getdestinations () {return destinations}, public void Setdestinations (destination[) destinations) {this.destinations = Destinations; } }

Package COM.DARCY.JMS; 
Import Java.util.HashMap; 
Import Java.util.Scanner;
Import javax.jms.Destination;   

Import Org.springframework.jms.core.JmsTemplate;     
public class Springpublish {private jmstemplate template; 
      
Private destination[] destinations;        
	 public void Chart () {Boolean chart = true;         

	int count = 0;             
		while (chart) {count + +; 
		Scanner cin=new Scanner (system.in);
             	SYSTEM.OUT.PRINTLN ("Input chat content, input n stop chatting");
	        String Text=cin.nextline ();
                if (Text.equals ("N")) {chart = false;
		} System.out.println ("I:" +text);         
	Sendchartmessage (Count,text); } protected void Sendchartmessage (int count, String strmessage) {Mymessagecreator creator = new
         Mymessagecreator (Count,strmessage);
Template.send (Destinations[0], creator);     
Public Jmstemplate GetTemplate () {return template;  }     

public void SetTemplate (jmstemplate template) {this.template = template;     
Destination[] Getdestinations () {return destinations;     
} public void Setdestinations (destination[] destinations) {this.destinations = destinations; 
 }   

}

message producer : Java code package COM.DARCY.JMS; Import Java.util.Date; Import javax.jms.JMSException; Import Javax.jms.MapMessage; Import Javax.jms.Message; Import javax.jms.Session; Import Org.springframework.jms.core.MessageCreator; public class Mymessagecreator implements Messagecreator {private int msgno; private String strmessage, public MYMESSAGECR Eator (int no,string parammessage) {This.msgno = no; this.strmessage = parammessage;} public message CreateMessage (Sessio N session) throws JMSException {Mapmessage message = Session.createmapmessage (); Message.setstring ("Date", new Date (). To String ()); Message.setstring ("message", strmessage); Message.setint ("Count", Msgno); return message; } }

package com.darcy.jms; import java.util.Date; 

Import javax.jms.JMSException; 
Import Javax.jms.MapMessage;
Import Javax.jms.Message; 
Import javax.jms.Session; 

Import Org.springframework.jms.core.MessageCreator;     
public class Mymessagecreator implements Messagecreator {private int msgno;       

Private String strmessage;         
	Public mymessagecreator (int no,string parammessage) {This.msgno = no;     
This.strmessage = Parammessage; Throws jmsexception {mapmessage mes 
createmessage

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.