Spring consolidates JMS

Source: Internet
Author: User

Draw on others (http://shmilyaw-hotmail-com.iteye.com/blog/2208966), combined with their own experience written, I use is ServiceMix activemq

I. Reliance

In order to run the example, we need to have a ACTIVEMQ server. ACTIVEMQ is as follows: http://activemq.apache.org/download.html download to a directory locally. Then go into the bin directory

Look at your computer is 32, or 64, open the corresponding folder, as follows

This way the ACTIVEMQ server is up and running. At this time, the default brokerurl of the server is: tcp://localhost:61616. After the server is running, if we want to know more about it, it can be viewed through a web console. Enter the following address in the browser: Http://localhost:8161/admin Enter the default user name admin and password admin

Hint: I am using servicemix whole, the bottom of the dependent jar may be different, access address http://localhost:8181/activemqweb Default user name: smx Password: smx page is the same, but the access path is different.

The following officially begins

two. Project required Jar (MAVEN)

        <dependency> <groupId>org.springframework</groupId> <artifactid>spri ng-context</artifactid> <version>4.1.6.RELEASE</version> </dependency> &L T;dependency> <groupId>org.springframework</groupId> <artifactid>spring-core&lt ;/artifactid> <version>4.1.6.RELEASE</version> </dependency> <dependency&            Gt <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> & lt;version>4.1.6.release</version> </dependency> <dependency> <groupid&gt ;org.apache.activemq</groupid> <artifactId>activemq-all</artifactId> &LT;VERSION&G t;5.11.1</version> </dependency> <dependency> <groupid>org.apache.service Mix.bundlEs</groupid> <artifactId>org.apache.servicemix.bundles.spring-core</artifactId> &L                         T;version>4.2.6.release_1</version> </dependency>

Three. Send a message

For spring, the core of the message is Jmstemplate, which is the basic configuration

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"XMLNS:JMS= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMShttp//www.springframework.org/schema/jms/spring-jms-4.0.xsd "><beanclass= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name= "Location" value= "Classpath:jms.properties"/> </bean> <bean id= "ConnectionFactory"class= "Org.apache.activemq.ActiveMQConnectionFactory" > <property name= "brokerurl" value= "${jms.brokerurl}"/> <property name= "UserName" value= "${jms.username}"/> <property name= "password" value= "${jms.password}" /> </bean> <bean id= "QueueName"class= "Org.apache.activemq.command.ActiveMQQueue" > <constructor-arg index= "0" value= "${jms.messagetopic}"/> </bean> <bean id= "Topicname"class= "Org.apache.activemq.command.ActiveMQTopic" > <constructor-arg index= "0" value= "${jms.messagetopic}"/> </bean> <bean id= "Jmstemplate"class= "Org.springframework.jms.core.JmsTemplate" > <property name= "connectionfactory" ref= "ConnectionFactory"/ > <!--subscribe to queue here ref= "QueueName" Subscription topic ref= "Topicname"-<property name= "Defaultdestination" R ef= "QueueName"/> </bean> <bean id= "Messagesender"class= "Test. Activemqmessagesender "> <constructor-arg index=" 0 "ref=" jmstemplate "/> </bean> <!--topic Monitoring <jms:listener-container container-type= "Default" destination-type= "topic"Connection-factory= "ConnectionFactory" acknowledge= "Auto" concurrency= "ten" > <jms:listener destination= "${jms.messageTo Pic} "ref=" MessageListener "method=" OnMessage "/> </jms:listener-container> <!--queue Listener--&LT;JM S:listener-container container-type= "Default" destination-type= "queue"Connection-factory= "ConnectionFactory" acknowledge= "Auto" concurrency= "ten" > <jms:listener destination= "${jms.messageTo Pic} "ref=" MessageListener "method=" OnMessage "/> </jms:listener-container> <bean id=" MessageListener "class= "Test. Activemqmessagelistener "/></beans>

Let's make an explanation for the previous content. First we need to build a connectionfactory of type org.apache.activemq.ActiveMQConnectionFactory. Here it defines the URL of the ACTIVEMQ server we need to access and the user name and password required to access it.

Then we define two beans, one is Org.apache.activemq.command.ActiveMQQueue's destination. It represents a queue that corresponds to a point-to-point communication. The destinationtopic that are defined later correspond to the topic that uses the broadcast mode of communication. We know that in the specification of JMS communication There are two ways to send messages, one is based on the point-to-point queue, mainly for a sender to send a message to a receiver case. The other is a broadcast-based topic that is used primarily to send messages to a number of recipients by a sender.

And then there's the key part that we're going to use, a pre-defined jmstemplate in spring, and its type is org.springframework.jms.core.JmsTemplate. The two main properties it needs to configure are connectionfactory and destination, respectively. This way, the template has solved the problem of which server to which to send. The rest is a bean that we define, which encapsulates the jmstemplate to send messages.

With these configurations, we actually use their code very simply. The implementation code for the Activemqmessagesender we define is as follows:

Importorg.springframework.jms.core.JmsTemplate;Importorg.springframework.stereotype.Component; @Component Public classActivemqmessagesenderImplementsMessagesender {Privatejmstemplate jmstemplate;  PublicActivemqmessagesender (jmstemplate jmstemplate) { This. jmstemplate =jmstemplate; } @Override Public voidsendMessage (String message) {jmstemplate.convertandsend (message); }}

In the above code, there are actually several ways to send a message jmstemplate, specifically, you can see my JMS introduction, which will be described in detail, we can refer to the document for the different types of messages sent to deal with. In the example we are simply sending a simple string.

To ensure a certain degree of loose coupling, an interface Messagesender is specifically defined:

 Public Interface Messagesender {    void  sendMessage (String message);}

Next, we try to send a simple message out:

Import Org.springframework.context.support.ClassPathXmlApplicationContext;  Public class TESTJMS {    publicstaticvoid  main (string[] args) {        new classpathxmlapplicationcontext ("Spring.xml");         = Ctx.getbean (messagesender.  Class);        Sender.sendmessage ("Hello 1612");        Ctx.close ();    }}

Now look at the page

Properties Code

Four. Receiving Messages asynchronously

The configuration files are in Spring.xml.

We define a Activemqmessagelistener class

Importjavax.jms.JMSException;ImportJavax.jms.Message;ImportJavax.jms.MessageListener;ImportJavax.jms.TextMessage; Public classActivemqmessagelistenerImplementsMessageListener {@Override Public voidonMessage (Message msg) {textmessage textmsg=(TextMessage) msg; Try{String message=Textmsg.gettext (); System.out.println ("Message:" +message); } Catch(jmsexception e) {e.printstacktrace (); }    }}

Execute the above TESTJMS and you'll receive a message here.

Note: There is also a synchronous receive message, do not write

Spring consolidates 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.