RabbitMQ and SPRINGMVC configuration use

Source: Internet
Author: User

In the MQ messaging framework, spring officially provides RABBITMQ use cases, using the springboot approach (MESSAGING-RABBITMQ); Next, we use the XML configuration to combine RABBITMQ into SPRINGMVC to play.

Environment: win10+jdk1.8+spring4.3+rabbitmq3.6.5

1. Install RABBITMQ service locally first
Please refer to the URL here, download the appropriate installation package and install it. Because the rabbit is based on the Erlang platform and borrows its concurrency, distributed features, the installation of the Erlang environment can be seen url! For subsequent convenience, you can configure its environment variables after installing RABBITMQ!

2. Look at the operating state of the RABBITMQ, if necessary, you can add the configuration of their own services, the command line to execute the following command
1> querying the status of RABBITMQ

Rabbitmqctl status

2> Query System User list, "Guest" default password is also "guest", its role is "Administrator", the system's highest authority, you can log in to the background management system, view all the system status information and related additions and deletions!

Rabbitmqctl list_users

3> the following command to enable the background management function, and then access "http://127.0.0.1:15672/", and then use the Super Administrator guest to log in to see and operate!

Rabbitmq-plugins Enable Rabbitmq_management

4> Create a new user!

Rabbitmqctl  add_user  Username  Password

5> Create a new virtual host directory, the equivalent of subsequent messaging operations space!

Rabbitmqctl Add_vhost Vhost_name

6> permissions for a user authorized by a Vhost!

Rabbitmqctl set_permissions-p Vhost_name Guest ". *" ". *" (this is an authorized Super Administrator to monitor)
Rabbitmqctl set_permissions-p/hisok A_host Hisoka "^hisoka-.*" ". *" ". *" (this is authorized to operate for ordinary users)
where ["^hisoka-.*"] is limited to the back of exchange and [Routingkey,queue]

2. Spring configuration, Project Source SSM
1> Introduction of Maven dependency

<!--=====================  RabbitMQ ==================---
<dependency>
    <groupId> org.springframework.amqp</groupid>
    <artifactId>spring-rabbit</artifactId>
    < version>1.6.2.release</version>
</dependency>
<!--=====================  / RabbitMQ ==================--

2> SPRINGMVC XML configuration related beans

<!--Create queue-to <bean id= "queue" class= "Org.springframework.amqp.core.Queue" > <construct Or-arg name= "name" value= "${mq.consumer.queue}"/> </bean> <!--the Exchange--and <bean id= " Topicexchange "class=" Org.springframework.amqp.core.TopicExchange "> <constructor-arg name=" name "value=" ${m Q.producer.exchange} "/> </bean> <!--Binding Proxy having Queue and Exchange--<bean id=
        "Bindingproxy" class= "Com.hisoka.MQueue.rabbit.BindingProxy" > <property name= "queue" ref= "queue"/> <property name= "Exchange" ref= "Topicexchange"/> </bean> <!--Binding the exchange and Queue With Routing.key--<bean id= "binding" factory-bean= "Bindingproxy" factory-method= "getbinding" &GT;&LT;/BEAN&G

    T <!--message Converter--<bean id= "Messageconverter" class= " Org.springframework.amqp.support.converter.SimpleMessageConverteR "/> <!--connection factory to connect RabbitMQ server--> <bean id=" ConnectionFactory "class=" Org.s Pringframework.amqp.rabbit.connection.CachingConnectionFactory "> <constructor-arg index=" 0 "value=" ${mq.ser Ver.host} "/> <constructor-arg index=" 1 "value=" ${mq.server.port} "/> <property name=" VirtualH OST "Value=" ${mq.server.virtualhost} "/> <property name=" username "value=" ${mq.username} "/> < Property name= "Password" value= "${mq.password}"/> </bean> <bean id= "rabbitadmin" class= "ORG.SPRINGFR

    Amework.amqp.rabbit.core.RabbitAdmin "> <constructor-arg ref=" connectionfactory "/> </bean> <!--rabbit template to send message--> <bean id= "rabbittemplate" class= "Org.springframework.amqp.rabbit.cor E.rabbittemplate "> <property name=" connectionfactory "ref=" connectionfactory "/> <property nam E= "Messageconverter" ref="Messageconverter"/> <property name= "Exchange" Value= "${mq.producer.exchange}"/> <property n
    Ame= "Routingkey" value= "${mq.producer.routing.key}"/> </bean> <!--message Listener Adapter <bean id= "Messagelisteneradapter" class= "  Org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter "> <constructor-arg name=" Delegate " ref= "Messagereceiver"/> </bean> <!--message Listener Adapter Container-<bean id= "sim Plemessagelistenercontainer "class=" Org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer " > <property name= "connectionfactory" ref= "ConnectionFactory"/> <property name= "MessageListene R "ref=" Messagelisteneradapter "/> <property name=" queuenames "value=" ${mq.consumer.queue} "/> </b Ean>

3> related to basic classes

/* Bind Exchange to queue and create and bind */package com.hisoka.MQueue.rabbit when not on rabbit
;

Import org.springframework.amqp.core.*;

/**
 * @author hinsteny
 * @date 2016/9/23
 * @copyright: Rights reserved.
 */Public
class Bindingproxy {

    private queue queue;

    Private Topicexchange exchange;

    public void Setqueue (queue queue) {
        this.queue = queue;
    }

    public void Setexchange (Topicexchange exchange) {
        This.exchange = Exchange;
    }

    Public Binding getbinding () {
        return Bindingbuilder.bind (queue). to (Exchange). With (Queue.getname ());
    }
}
/* Message Receiving Processor */package Org.hinsteny.service.impl.MQ;
Import Com.hisoka.MQueue.rabbit.MessageListenerProxy;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;

Import org.springframework.stereotype.Component;
Import java.util.ArrayList;

Import java.util.List;
 /** * @author Hinsteny * @date 2016/9/23 * @copyright: Rights reserved. */@Component ("Messagereceiver") public class Mymessagereceiver extends messagelistenerproxy{private static final Lo

    Gger logger = Loggerfactory.getlogger (Mymessagereceiver.class);

    Private volatile list<string> messages = new ArrayList (64);
        Public list<string> getmessages () {list<string> result = new ArrayList (messages);
        This.messages.clear ();
    return result; } @Override Public Object handlemessage (string messageId, String messagecontent, String queue) {if (Logg Er.isinfoenabled ()) logger.info ("Receive message ID {}, queue {} and content is {}", MessageId, queue, mesSagecontent);
        This.messages.add (Messages.tostring ());
    return true;
 }
}

3. Web Test

/*web rest action*/
    @Get ("/testmq/send")
    @ResponseBody public
    WebResponse TESTSENDMQ ( HttpServletRequest request, @RequestParam (name = "name") String name, httpservletresponse response) {
        Boolean result = Mqservice.sendmessage (name);
        return webresponse.success (result);
    }

    @Get ("/testmq/get")
    @ResponseBody public
    WebResponse TESTGETMQ (httpservletrequest request, HttpServletResponse response) {
        list<string> result = Mqservice.getmessage ();
        return webresponse.success (result);
    }
/*service*/package Org.hinsteny.service.impl.MQ;
Import Org.hinsteny.service.MQService;
Import Org.springframework.amqp.rabbit.core.RabbitTemplate;
Import org.springframework.beans.factory.annotation.Autowired;

Import Org.springframework.stereotype.Service;

Import java.util.List;
 /** * @author Hinsteny * @date 2016/9/22 * @copyright: Rights reserved.

    */@Service public class Mqserviceimpl implements mqservice{@Autowired Mymessagereceiver receiver;

    @Autowired rabbittemplate rabbittemplate;
        @Override public boolean sendMessage (String message) {rabbittemplate.convertandsend (message);
    return true;
    } @Override Public list<string> getMessage () {return receiver.getmessages (); }
}

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.