Spring Mvc整合Rabbitmq的简单例子

一、RabbitMQ的介绍

Java菜鸟一名,最近在研究RabbitMQ,记录一下学到的东西。

网上有很多的RabbitMQ的介绍和资料,这边我就简单复制一下,专业一点。
RabbitMQ是一个在AMQP协议标准基础上完整的,可服用的企业消息系统。他遵循Mozilla Public License开源协议。采用 Erlang 实现的工业级的消息队列(MQ)服务器。
AMQP,即Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计。消息中间件主要用于组件之间的解耦,消息的发送者无需知道消息使用者的存在,反之亦然。
RabbitMQ是一个开源的AMQP实现,服务器端用Erlang语言编写,支持多种客户端,如:Python、Ruby、.NET、Java、JMS、C、PHP、ActionScript、XMPP、STOMP等,支持AJAX。用于在分布式系统中存储转发消息,在易用性、扩展性、高可用性等方面表现不俗。

二、RabbitMQ的安装

windows环境下的安装。
安装基本教程也很多,没什么大问题,按部就班就行。

RabbitMQ是Erlang开发的,先要安装Erlang
http://www.erlang.org/downloads
配置环境变量Erlang home目录
ERLANGH_HOME = Erlang安装目录

安装RabbitMQ
https://www.rabbitmq.com/(我习惯上下载解压版)

启动RabbitMQ(在命令行界面,cd到RabbitMQ的sbin目录)


  • 以应用方式启动

rabbitmq-server -detached(后台启动)
rabbitmq-server(直接启动,如果关闭命令行窗口,应用就回关闭)
rabbitmqctl stop(关闭RabbitMQ

  • 以服务方式启动
    rabbitmq-service install(安装服务)
    rabbitmq-service start 启动服务
    rabbitmq-service stop 关闭服务
    rabbitmqctl stop 关闭RabbitMQ

  • 安装RabbitMQ管理界面插件
    rabbitmq-plugins enable rabbitmqmanagement
    打开管理界面 http://localhost:15672/
    Spring Mvc整合Rabbitmq的简单例子_第1张图片

    三、Spring Mvc + RabbitMQ

    spring-mvc.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <context:component-scan base-package="com.young.controller" />
    
        <mvc:annotation-driven />
    
        <mvc:resources location="/js/" mapping="/js/**" />
        
    
        
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        bean>
    
    beans>

    spring-rabbitmq.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:rabbit="http://www.springframework.org/schema/rabbit"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.6.xsd">
    
    
        
        
        
        <rabbit:connection-factory id="connectionFactory"
            virtual-host="${amqp.virtual-host}" host="${amqp.host}" username="${amqp.username}"
            password="${amqp.password}" port="${amqp.port}" />
    
        <rabbit:admin connection-factory="connectionFactory" />
    
        
        <rabbit:queue id="messageQueue" durable="true"
            auto-delete="false" exclusive="false" name="messageQueue" />
    
        
        
        <rabbit:topic-exchange name="messageExchange"
            durable="true" auto-delete="false" id="messageExchange">
            <rabbit:bindings>
                <rabbit:binding pattern="message.*" queue="messageQueue">rabbit:binding>
            rabbit:bindings>
        rabbit:topic-exchange>
    
        <rabbit:template exchange="messageExchange" id="rabbitTemplate"
            connection-factory="connectionFactory" message-converter="jsonMessageConverter" />
    
        
        <bean id="jsonMessageConverter"
            class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />
    
        <rabbit:listener-container
            connection-factory="connectionFactory" acknowledge="auto">
            <rabbit:listener ref="messageConsumer" queues="messageQueue" />
        rabbit:listener-container>
    
        <bean id="messageSender" class="com.young.amqp.MessageSender">
            <property name="amqpTemplate" ref="rabbitTemplate">property>
            
        bean>
    
        <bean id="messageConsumer" class="com.young.amqp.MessageConsumer" />
    
    beans>

    spring-resource.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        
        <bean id="propertyPlaceholderConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath:prop/amqp.propertiesvalue>
                list>
            property>
        bean>
    
    beans>

    amqp.properties

    /# rabbitmq setting
    /# 用除了guest的用户连接时,要在rabbitmq客户端中设置用户访问虚拟主机的权限
    amqp.host=localhost
    amqp.username=young
    amqp.password=123456
    amqp.port=5672
    
    /# 虚拟主机
    amqp.virtual-host=test

    消息生产者

    package com.young.amqp;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.amqp.core.AmqpTemplate;
    
    public class MessageSender {
    
        private Logger logger = LoggerFactory.getLogger(MessageSender.class);
    
        private AmqpTemplate amqpTemplate;
    
        private String routingKey;
    
        public AmqpTemplate getAmqpTemplate() {
            return amqpTemplate;
        }
    
        public void setAmqpTemplate(AmqpTemplate amqpTemplate) {
            this.amqpTemplate = amqpTemplate;
        }
    
        public String getRoutingKey() {
            return routingKey;
        }
    
        public void setRoutingKey(String routingKey) {
            this.routingKey = routingKey;
        }
    
        public void sendDataToQueue(Object obj) {
            logger.info("to send message:{}",obj);
            amqpTemplate.convertAndSend(this.routingKey, obj);
        }
    
    }

    消息消费者

    package com.young.amqp;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.amqp.core.Message;
    import org.springframework.amqp.core.MessageListener;
    
    public class MessageConsumer implements MessageListener {
    
        private Logger logger = LoggerFactory.getLogger(MessageConsumer.class);
    
        @Override
        public void onMessage(Message message) {
            logger.info("receive message:{}",message);
        }
    
    }

    Controller中测试

    @RequestMapping(value = "/doValid")
    @ResponseBody
    public String doValid(@RequestBody ValidUser user) {
    
        // 设置RoutingKey,匹配message.*即可
        messageSender.setRoutingKey("message.test");
        // 发送消息
        messageSender.sendDataToQueue("hello world");
    
        return "{\"key\" : \"value\"}";
    }

    四、一些问题

    使用自定义用户登录时会出现权限不够,可能是下面这个问题。
    Spring Mvc整合Rabbitmq的简单例子_第2张图片
    如果permissions的权限是’.*’,应该是命令行添加权限造成的,先clear,在点下面的Set permission。变成图中那样就可以了。
    口才不咋滴!!!尴尬!
    完整的Demo:http://download.csdn.net/detail/u013480675/9704735

    你可能感兴趣的:(Spring Mvc整合Rabbitmq的简单例子)