"RABBITMQ series" Spring MVC integration RABBITMQ

Source: Internet
Author: User
Tags object object rabbitmq

First, install RABBITMQ1 under Linux, install Erlang environment
wget http://erlang.org/download/otp_src_18.2.1.tar.gz  tar xvfz otp_src_18.2.1.tar.gz   CD otp_src_18.2.1./ Configure   
2, Installation RABBITMQ
wget http://www.rabbitmq.com/releases/rabbitmq-server/vx.x.x/rabbitmq-server-generic-unix-x.x.x.tar.xz  // XY file Compression tool yum install XZ  //decompression xz-d rabbitmq-server-generic-unix-x.x.x.tar.xz  TAR-XVF rabbitmq-server-generic-unix-x.x.x.tar//move it to/usr/local/under your own custom Cp-r RABBITMQ_SERVER-X.X.X/USR/LOCAL/RABBITMQ  //Change environment variable Vi/etc/profileexport path=/usr/local/rabbitmq/sbin: $PATH  source/etc/profile// Enable MQ management mode Rabbitmq-plugins enable Rabbitmq_management   #启动后台管理  rabbitmq-server-detached   #后台运行rabbitmq  //Set port number for external use iptables-i input-p tcp--dport 15672-j ACCEPT  
3. Add Users and Permissions
Add user rabbitmqctl Add_user admin admin//Add permissions rabbitmqctl set_permissions-p "/" admin ". *". * ". *"//Add user role Rabbitmqctl SE T_user_tags Admin Administrator

 

Two, Spring MVC integration RabbitMQ1, add Pom.xml dependent jar Package
<!--https://mvnrepository.com/artifact/org.springframework.amqp/spring-rabbit--        <dependency>            <groupId>org.springframework.amqp</groupId>            <artifactid>spring-rabbit</ artifactid>            <version>1.7.5.RELEASE</version>        </dependency>
2. Add Configuration Applicationcontext.xml
<!--configuration RABBITMQ start-to-<bean id= "CONNECTIONFACTORYMQ" class= " Org.springframework.amqp.rabbit.connection.CachingConnectionFactory "> <constructor-arg value=" 192.168.181.201 "/> <property name=" username "value=" admin "/> <property name=" password "value=" ad    Min "/> <property name=" host "value=" 192.168.181.201 "/> <property name=" port "value=" 5672 "/> </bean> <bean id= "rabbitadmin" class= "Org.springframework.amqp.rabbit.core.RabbitAdmin" > <const Ructor-arg ref= "Connectionfactorymq"/> </bean> <!--Create Rabbittemplate message template class--<bean id= "Rabbittem Plate "class=" org.springframework.amqp.rabbit.core.RabbitTemplate "> <constructor-arg ref=" Connectionfactorymq "/> </bean> <!--Create a message converter for simplemessageconverter--> <bean id=" Serializermessage Converter "class=" Org.springframework.amqp.support.converter.SimpleMessageConverter "> </bean> <! --Create a persistent queue--<bean id= "queue" class= "Org.springframework.amqp.core.Queue" > <constructor-arg index= "0" value= "testqueue" ></constructor-arg> <constructor-arg index= "1" value= "true" ></constructor-a  Rg> <constructor-arg index= "2" value= "false" ></constructor-arg> <constructor-arg index= "3" Value= "true" ></constructor-arg> </bean> <!--Create a type of exchanger and persist--<bean id= "Topicexchange" cl ass= "Org.springframework.amqp.core.TopicExchange" > <constructor-arg index= "0" value= "Testexchange" ></ Constructor-arg> <constructor-arg index= "1" value= "true" ></constructor-arg> <constructor-a RG index= "2" value= "false" ></constructor-arg> </bean> <util:map id= "Arguments" > </util:ma P> <!--binding Exchanger Queue--<bean id= "binding" class= "org.springframework.amqp.core.Binding" > <const Ructor-arg index= "0" vaLue= "Testqueue" ></constructor-arg> <constructor-arg index= "1" value= "QUEUE" ></constructor-arg&        Gt <constructor-arg index= "2" value= "Testexchange" ></constructor-arg> <constructor-arg index= "3" value= "Testqueue" ></constructor-arg> <constructor-arg index= "4" value= "#{arguments}" ></ Constructor-arg> </bean> <!--processing class for receiving messages--<bean id= "Rqmconsumer" class= "Com.slp.mq.RmqConsumer "></bean> <bean id=" Messagelisteneradapter "class=" Org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter "> <constructor-arg ref="        Rqmconsumer "/> <property name=" Defaultlistenermethod "value=" Rmqproducermessage "></property> <property name= "Messageconverter" ref= "Serializermessageconverter" ></property> </bean> <!--for The message listens to the container class Simplemessagelistenercontainer, and the listener queue queues can pass multiple--<bean id= "Listenercontainer" Class= "Org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer" > <property name= "Queues" ref = "queue" ></property> <property name= "ConnectionFactory" ref= "CONNECTIONFACTORYMQ" ></property > <property name= "MessageListener" ref= "Messagelisteneradapter" ></property> </bean> < Bean id= "Rmqproducer" class= "Com.slp.mq.RmqProducer" ></bean> <!--configuration Rabbitmq End--
3. Message entity class
Package Com.slp.mq;import java.io.*;/** * @author SANGLP * @create 2018-02-06 * @desc Rabbit Message class **/public class Rabb    Itmessage implements Serializable {/** * parameter type */private class<?>[] paramtypes;    /** * EXCHANGER */private String exchange;    Private object[] params;    /** * Route key */private String Routekey; Public Rabbitmessage () {} public Rabbitmessage (string Exchange, String routekey,object...params) {This.exc        hange = Exchange;        This.params = params;    This.routekey = Routekey; } @SuppressWarnings ("Rawtypes") public rabbitmessage (String exchange,string routekey,string Methodname,object...para        ms) {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 ();       ObjectOutput Oos;           try {oos = new ObjectOutputStream (BAOs);           Oos.writeobject (this);           Oos.close ();       res = Baos.tobytearray ();       } catch (IOException e) {e.printstacktrace ();   } return res;    } public class<?>[] Getparamtypes () {return paramtypes;    } public void Setparamtypes (class<?>[] paramtypes) {this.paramtypes = Paramtypes;    } public String Getexchange () {return exchange;    public void Setexchange (String exchange) {this.exchange = Exchange;    } public object[] Getparams () {return params;    } public void SetParams (object[] params) {this.params = params;    } public String Getroutekey () {return routekey;    } public void Setroutekey (String routekey) {this.routekey = Routekey; }} 

4. Producers
Package Com.slp.mq;import Org.springframework.amqp.rabbit.core.rabbittemplate;import javax.annotation.Resource;/* * * @author SANGLP * @create 2018-02-06 14:19 * @desc producer **/public class Rmqproducer {    @Resource    private Rabbitte Mplate rabbittemplate;    /**     * Send Message     * @param msg */public    void SendMessage (Rabbitmessage msg) {        System.out.println ( Rabbittemplate.getconnectionfactory (). GetHost ());        System.out.println (Rabbittemplate.getconnectionfactory (). Getport ());        System.out.println ("msg" +msg);        Rabbittemplate.convertandsend (Msg.getexchange (), Msg.getroutekey (), msg);        SYSTEM.OUT.PRINTLN ("Send Complete");}    }

  

5. Consumers
Package com.slp.mq;/** * @author SANGLP * @create 2018-02-06 14:23 * @desc Consumer **/public class Rmqconsumer {public    vo ID rmqproducermessage (Object object) {        System.out.println ("Pre-consumption");        Rabbitmessage rabbitmessage = (rabbitmessage) object;        System.out.println (Rabbitmessage.getexchange ());        System.out.println (Rabbitmessage.getroutekey ());        System.out.println (Rabbitmessage.getparams (). toString ());}    }

  

6. Test class
Package Com.slp;import Com.slp.mq.rabbitmessage;import Com.slp.mq.rmqconsumer;import com.slp.mq.rmqproducer;import Org.junit.before;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.filesystemxmlapplicationcontext;import Java.util.hashmap;import java.util.map;/** * @author SANGLP * @create 2018-02-06 14:36 * @desc MQ Test class **/public class Mqtest {private rmqproduce    R Rmqproducer;    Private Rmqconsumer Rqmconsumer; @Before public void SetUp () throws Exception {//classpathxmlapplicationcontext context = new Classpathxmlapplic        Ationcontext ("D:/web-back/web-back/myweb/web/web-inf/applicationcontext.xml");        Context.start ();        String path= "Web/web-inf/applicationcontext.xml";        ApplicationContext context = new Filesystemxmlapplicationcontext (path);        Rmqproducer = (rmqproducer) context.getbean ("Rmqproducer");    Rqmconsumer = (Rmqconsumer) context.getbean ("Rqmconsumer"); } @TeSt public void Test () {String exchange = "Testexchange";        String Routekey = "Testqueue";       String methodName = "Test";            parameter for (int i=0;i<10;i++) {map<string,object> param=new hashmap<string, object> ();            Param.put ("Data", "Hello");            Rabbitmessage msg=new rabbitmessage (exchange,routekey, MethodName, param);        Send Message Rmqproducer.sendmessage (msg);    }//Rqmconsumer.rmqproducermessage (msg); }}

 

Operation Result:

Before the consumer is opened:

 

  

  

  

"RABBITMQ series" Spring MVC integration RABBITMQ

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.