RABBITMQ and SPRINGMVC integration and implementation of Send message and receive message (persistence) Scheme II

Source: Internet
Author: User
Tags rabbitmq

RABBITMQ about the introduction, the previous article has been introduced, this is not introduced, the direct description of RABBITMQ and SPRINGMVC integration and implementation to send messages and receive messages (persistence).

Using Spring-rabbit to send messages and receive messages, we use MAVEN to manage Jar packs, introducing jar packs into Maven's pom.xml files

<span style= "FONT-SIZE:18PX;" >  <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId> spring-rabbit</artifactid>
         <version>1.3.6.RELEASE</version>
    </dependency></ Span>
1. Realization of producer

The first step: is to set the call to install RABBITMQ IP, port, etc.

Configure a Global.properties file


Step two: Read the global.properties file through SPRINGMVC

<span style= "FONT-SIZE:18PX;" ><!--Injection Property file-->  
    <bean id= "Propertyconfigurer" class= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ">  
        <property name=" Locations " >  
            <list>  
                <value>classpath:global.properties</value>  
            </list>  
        </ property>  
    </bean>  </span>

Step Three: Configure the RABBITMQ server connection, create the Rabbittemplate message template class, and so on, and add the following in the SPRINGMVC configuration file

<bean id= "RmqProducer2" class= "Cn.test.spring.rabbitmq.RmqProducer" ></bean>

<span style= "font-size:18px;" > <!--Create connection class--> <bean id= "ConnectionFactory" class= "Org.springframework.amqp.rabbit.connection.CachingC" Onnectionfactory "> <constructor-arg value=" localhost "/> <property name=" username "value=" ${rmq.manager.user} "/> <property name= password" value= "${rmq.manager.password}"/>  
     
    Rty name= "host" value= "${rmq.ip}"/> <property name= "port" value= "${rmq.port}"/> </bean> <bean id= "Rabbitadmin" class= "Org.springframework.amqp.rabbit.core.RabbitAdmin" > <constructor -arg ref= "ConnectionFactory"/> </bean> <!--Create Rabbittemplate message template class--> <bean id= "Rab Bittemplate "class=" org.springframework.amqp.rabbit.core.RabbitTemplate "> <constructor-arg ref=" connectio Nfactory "></constructor-arg> </bean> </span> 
Step Fourth: Implement message class entities and send messages

Class entity

<span style= "FONT-SIZE:18PX;" >/** * Message */public class Rabbitmessage implements Serializable {private static final long Serialversionuid =-6
	
	487839157908352120L;
	
	Private class<?>[] paramtypes;//parameter type private String exchange;//switch private object[] params; Private string routekey;//route key public Rabbitmessage () {} public rabbitmessage (String exchange,string routekey,object. ..		
		params) {this.params=params;
		This.exchange=exchange;
	This.routekey=routekey; @SuppressWarnings ("Rawtypes") public rabbitmessage (String exchange,string routekey,string methodname,object ...		
		params) {this.params=params;
		This.exchange=exchange;
		This.routekey=routekey;
		int len=params.length;
		Class[] Clazzarray=new Class[len];
		for (int i=0;i<len;i++) clazzarray[i]=params[i].getclass ();
	This.paramtypes=clazzarray;
		Public byte[] Getserialbytes () {byte[] res=new byte[0];
		Bytearrayoutputstream baos=new Bytearrayoutputstream (); ObjectoutputstreaM Oos;
			try {oos = new ObjectOutputStream (BAOs);
			Oos.writeobject (this);
			Oos.close ();
		Res=baos.tobytearray ();
		catch (IOException e) {e.printstacktrace ();
	return res;
	Public String Getroutekey () {return routekey;
	Public String Getexchange () {return exchange;
	public void Setexchange (String exchange) {this.exchange = Exchange;
	} public void Setroutekey (String routekey) {this.routekey = Routekey;
	Class<?>[] Getparamtypes () {return paramtypes;
	Object[] Getparams () {return params; }} </span>
Send a message

<span style= "FONT-SIZE:18PX;" >/** * * * * * */public

class rmqproducer
{
	
	@Resource
	private rabbittemplate Rabbittemplate;
	
	/**
	 * Send a message
	 * @param
	 msg
	/public void SendMessage (Rabbitmessage  msg)
	{
		try {
			System.out.println (Rabbittemplate.getconnectionfactory (). GetHost ());
			System.out.println (Rabbittemplate.getconnectionfactory (). Getport ());
			Send Information
		    rabbittemplate.convertandsend (Msg.getexchange (), Msg.getroutekey (), msg);
		 
		} catch (Exception e) {
		}
		
		
	}
	
} </span>
Description

1. Rabbittemplate.convertandsend (Msg.getexchange (), Msg.getroutekey (), MSG);

The method of sending calls in the source code, some send messages to help us achieve the best.


2. The above code implementation does not declare the exchanger and queue, RABBITMQ and queue their binding relationship, if the RABBITMQ manager does not have the corresponding switches and queues are not new and associated, need to manually associate.


We can also use code to declare:

Rabbitadmin to declare: Eclareexchange method parameter is a switch

Bindingbuilder.bind (queue). to (Directexchange). with (queuename);//bind queue to Exchange

Rabbitadmin.declarebinding (binding);//declaring binding relationship

The source code has these methods:

This enables the binding of the exchanger and the queue

The switch can be declared as persistent and will not be automatically deleted after use.

Description of the Topicexchange parameter: name is the name of the exchanger, Durable:true is persisted autodelete:false is not deleted after use

Source:


Queues can also be declared as persistent


Fifth step: Implement Test class

<span style= "FONT-SIZE:18PX;" > @Resource
	private rmqproducer rmqProducer2;
	
	@Test public
	void Test () throws IOException
	{


			string exchange= "Testexchange";////converter
			String Routekey = "Testqueue";//Queue
			String methodname= "test";//called method
			/Parameter
			map<string,object> param=new HashMap <string, object> ();
			Param.put ("Data", "Hello");
			
			Rabbitmessage  msg=new rabbitmessage (exchange,routekey, MethodName, param);
			Send Message
			rmqproducer2.sendmessage (msg);
			
	</span>
Result: RABBITMQ has a message

2. Consumers

Step One: RABBITMQ server connection These have been introduced in the producer side, this is not introduced, we want to configure RABBITMQ server connection, create Rabbittemplate message template class, message converter, message converter listener, etc. In the SPRINGMVC configuration file, add the following

<span style= "FONT-SIZE:18PX;" > <!--Create connection class--> <bean id= "ConnectionFactory" class= "Org.springframework.amqp.rabbit.connection.CachingC" Onnectionfactory "> <constructor-arg value=" localhost "/> <property name=" username "value=" ${rmq.manager.user} "/> <property name= password" value= "${rmq.manager.password}"/>  
     
    Rty name= "host" value= "${rmq.ip}"/> <property name= "port" value= "${rmq.port}"/> </bean> <bean id= "Rabbitadmin" class= "Org.springframework.amqp.rabbit.core.RabbitAdmin" > <constructor -arg ref= "ConnectionFactory"/> </bean> <!--Create Rabbittemplate message template class--> <bean id= "Rab Bittemplate "class=" org.springframework.amqp.rabbit.core.RabbitTemplate "> <constructor-arg ref=" connectio Nfactory "></constructor-arg> </bean> <!--Create a message converter for Simplemessageconverter--> <bean id= "Serializermessageconverter" class= "  
    Org.springframework.amqp.support.converter.SimpleMessageConverter ></bean> <!--set persistent queues--> <bean id= "queue" class= "Org.springframework.amqp.core.Queue" > <constructor-arg index= "0" value= "TESTQ  
        Ueue "></constructor-arg> <constructor-arg index=" 1 "value=" true "></constructor-arg> <constructor-arg index= "2" value= "false" ></constructor-arg> <constructor-arg index= "3" value= " False "></constructor-arg> </bean> <!--Create the type of exchanger and persist--> <bean id=" Topice Xchange "class=" Org.springframework.amqp.core.TopicExchange "> <constructor-arg index=" 0 "value=" Testexchang  
        E "></constructor-arg> <constructor-arg index=" 1 "value=" true "></constructor-arg> <constructor-arg index= "2" value= "false" ></constructor-arg> </bean> <util:map id= "Arguments" > </util:map> <!--binding exchanger, queue--> <bean Id= "binding" class= "org.springframework.amqp.core.Binding" > <constructor-arg index= "0" value= "Testqueue" & Gt;</constructor-arg> <constructor-arg index= "1" value= "QUEUE" ></constructor-arg> ; Constructor-arg index= "2" value= "Testexchange" ></constructor-arg> <constructor-arg index= "3" value= "t Estqueue "></constructor-arg> <constructor-arg index=" 4 "value=" #{arguments} "></constructor-arg > </bean> <!--processing class for receiving messages--> <bean id= "Rmqconsumer" class= "Cn.test.sprin" G.rabbitmq.rmqconsumer "></bean> <bean id=" Messagelisteneradapter "class=" ORG.SPRINGFRAMEWORK.AMQP. Rabbit.listener.adapter.MessageListenerAdapter "> <constructor-arg ref=" Rmqconsumer "/> &LT;PR Operty name= "DefaultlistEnermethod "value=" Rmqproducermessage "></property> <property name=" Messageconverter "ref=" serializer Messageconverter "></property> </bean> <!--container class Simplemessagelistenercontainer for message monitoring Queue queues can pass multiple--> <bean id= "Listenercontainer" class= Listenercontainer "> <property name=" Queues "ref=" queue "></property> <property name=" ConnectionFactory "ref=" ConnectionFactory "></property> <property name=" MessageListener "ref=" message ListenerAdapter "></property> </bean> </span>

Description

Queues in 1.org.springframework.amqp.rabbit.listener.simplemessagelistenercontainer can pass in multiple queues

2.org.springframework.amqp.rabbit.listener.adapter.messagelisteneradapter

Which consumer adapter to handle, parameter Defaultlistenermethod is the default calling method to process the message.

3. The persistence of exchangers and queues has been introduced by producers.

4.org.springframework.amqp.core.binding the binding of this class, when configured in the SPRINGMVC configuration file,

destinationtype This parameter should be noted.

Source:

Step Two: Process messages

<span style= "FONT-SIZE:18PX;" >/**
 * Consumer
 *
/public class Rmqconsumer  
{public
	void Rmqproducermessage (object) {
		
		rabbitmessage rabbitmessage= (rabbitmessage) object;
		
		System.out.println (Rabbitmessage.getexchange ());
		System.out.println (Rabbitmessage.getroutekey ());
		System.out.println (Rabbitmessage.getparams (). toString ());
		
		
	}
	
	
	
	
			
	
</span>


This error may be reported during the boot process, possibly because your switch and queue are not configured properly.







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.