一、RabbitMQ与Spring集成

 准备工作:

分别新建名为RabbitMQSpringProducer和RabbitMQSpringConsumer的maven web工程

在pom.xml文件里面引入如下依赖:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.study.demo</groupId>
  5. <artifactId>RabbitMQSpringProducer</artifactId>
  6. <packaging>war</packaging>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>RabbitMQSpringProducer Maven Webapp</name>
  9. <url>http://maven.apache.org</url>
  10. <dependencies>
  11. <dependency>
  12. <groupId>junit</groupId>
  13. <artifactId>junit</artifactId>
  14. <version>3.8.1</version>
  15. <scope>test</scope>
  16. </dependency>
  17.  
  18. <dependency>
  19. <groupId>javax</groupId>
  20. <artifactId>javaee-web-api</artifactId>
  21. <version>7.0</version>
  22. <scope>provided</scope>
  23. </dependency>
  24. <dependency>
  25. <groupId>commons-logging</groupId>
  26. <artifactId>commons-logging</artifactId>
  27. <version>1.2</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.slf4j</groupId>
  31. <artifactId>jcl-over-slf4j</artifactId>
  32. <version>1.7.5</version>
  33. </dependency>
  34.  
  35. <dependency>
  36. <groupId>org.springframework</groupId>
  37. <artifactId>spring-webmvc</artifactId>
  38. <version>4.3.11.RELEASE</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.springframework</groupId>
  42. <artifactId>spring-aop</artifactId>
  43. <version>4.3.11.RELEASE</version>
  44. </dependency>
  45.  
  46. <dependency>
  47. <groupId>javax.servlet</groupId>
  48. <artifactId>jstl</artifactId>
  49. <version>1.2</version>
  50. </dependency>
  51.  
  52. <!--日志 -->
  53. <dependency>
  54. <groupId>org.slf4j</groupId>
  55. <artifactId>slf4j-api</artifactId>
  56. <version>1.7.5</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>log4j</groupId>
  60. <artifactId>log4j</artifactId>
  61. <version>1.2.16</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.slf4j</groupId>
  65. <artifactId>jcl-over-slf4j</artifactId>
  66. <version>1.7.5</version>
  67. </dependency>
  68. <dependency>
  69. <groupId>ch.qos.logback</groupId>
  70. <artifactId>logback-classic</artifactId>
  71. <version>1.0.13</version>
  72. </dependency>
  73. <dependency>
  74. <groupId>ch.qos.logback</groupId>
  75. <artifactId>logback-core</artifactId>
  76. <version>1.0.13</version>
  77. </dependency>
  78. <dependency>
  79. <groupId>ch.qos.logback</groupId>
  80. <artifactId>logback-access</artifactId>
  81. <version>1.0.13</version>
  82. </dependency>
  83.  
  84. <!--JSON -->
  85. <dependency>
  86. <groupId>org.codehaus.jackson</groupId>
  87. <artifactId>jackson-mapper-asl</artifactId>
  88. <version>1.9.13</version>
  89. </dependency>
  90. <dependency>
  91. <groupId>org.codehaus.jackson</groupId>
  92. <artifactId>jackson-core-asl</artifactId>
  93. <version>1.9.13</version>
  94. </dependency>
  95. <dependency>
  96. <groupId>com.fasterxml.jackson.core</groupId>
  97. <artifactId>jackson-databind</artifactId>
  98. <version>2.8.4</version>
  99. </dependency>
  100.  
  101. <!-- RabbitMQ -->
  102. <dependency>
  103. <groupId>com.rabbitmq</groupId>
  104. <artifactId>amqp-client</artifactId>
  105. <version>5.0.0</version>
  106. </dependency>
  107. <dependency>
  108. <groupId>org.springframework.amqp</groupId>
  109. <artifactId>spring-rabbit</artifactId>
  110. <version>2.0.0.RELEASE</version>
  111. </dependency>
  112. </dependencies>
  113. <build>
  114. <finalName>RabbitMQSpringProducer</finalName>
  115. <plugins>
  116. <plugin>
  117. <groupId>org.apache.maven.plugins</groupId>
  118. <artifactId>maven-compiler-plugin</artifactId>
  119. <version>2.3.2</version>
  120. <configuration>
  121. <source>1.8</source>
  122. <target>1.8</target>
  123. </configuration>
  124. </plugin>
  125. </plugins>
  126. <resources>
  127. <resource>
  128. <directory>${basedir}/src/main/java</directory>
  129. <includes>
  130. <include>**/*.xml</include>
  131. </includes>
  132. </resource>
  133. </resources>
  134. </build>
  135. </project>

与Spring集成步骤:

配置文件中增加命名空间:
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-2.0.xsd

配置文件中的配置
1) 连接工厂配置
2) <rabbit:admin>
3) 声明队列
4) 声明交换器
5) 队列和交换器进行绑定
6) 生产者端要声明RabbitmqTemplate

1. 在工程RabbitMQSpringProducer里面新建/RabbitMQSpringProducer/src/main/java/applicationContext.xml的配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ -->
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xmlns:jee="http://www.springframework.org/schema/jee"
  8. xmlns:p="http://www.springframework.org/schema/p"
  9. xmlns:aop="http://www.springframework.org/schema/aop"
  10. xmlns:context="http://www.springframework.org/schema/context"
  11. xmlns:task="http://www.springframework.org/schema/task"
  12. xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  13. xsi:schemaLocation="http://www.springframework.org/schema/beans
  14. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  15. http://www.springframework.org/schema/context
  16. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  17. http://www.springframework.org/schema/jee
  18. http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
  19. http://www.springframework.org/schema/mvc
  20. http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  21. http://www.springframework.org/schema/tx
  22. http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  23. http://www.springframework.org/schema/aop
  24. http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  25. http://www.springframework.org/schema/task
  26. http://www.springframework.org/schema/task/spring-task-4.0.xsd
  27. http://www.springframework.org/schema/rabbit
  28. http://www.springframework.org/schema/rabbit/spring-rabbit-2.0.xsd">
  29.  
  30. <!-- rabbitMQ配置 -->
  31. <bean id="rabbitConnectionFactory"
  32. class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
  33. <constructor-arg value="127.0.0.1"/>
  34. <property name="username" value="guest"/>
  35. <property name="password" value="guest"/>
  36. <property name="channelCacheSize" value="8"/>
  37. <property name="port" value="5672"></property>
  38. </bean>
  39. <!--Spring的rabbitmq admin-->
  40. <rabbit:admin connection-factory="rabbitConnectionFactory"/>
  41.  
  42. <!--生产者创建队列-->
  43. <rabbit:queue name="p_create_queue" durable="false"/>
  44.  
  45. <!--fanout交换器-->
  46. <rabbit:fanout-exchange name="fanout-exchange"
  47. xmlns="http://www.springframework.org/schema/rabbit" durable="false">
  48. <rabbit:bindings>
  49. <rabbit:binding queue="p_create_queue"></rabbit:binding>
  50. </rabbit:bindings>
  51. </rabbit:fanout-exchange>
  52.  
  53. <!--topic交换器-->
  54. <rabbit:topic-exchange name="topic-exchange"
  55. xmlns="http://www.springframework.org/schema/rabbit" durable="false">
  56. </rabbit:topic-exchange>
  57. <!-- rabbitTemplate 消息模板类 -->
  58.  
  59. <!--定义Spring的RabbitMQ的连接模板 -->
  60. <bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate">
  61. <constructor-arg ref="rabbitConnectionFactory"></constructor-arg>
  62. </bean>
  63.  
  64. </beans>

3. 在工程RabbitMQSpringProducer里面新建/RabbitMQSpringProducer/src/main/java/spring-mvc.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ -->
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xmlns:tx="http://www.springframework.org/schema/tx"
  8. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  9. xsi:schemaLocation="http://www.springframework.org/schema/aop
  10. http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  11. http://www.springframework.org/schema/beans
  12. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  13. http://www.springframework.org/schema/context
  14. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  15. http://www.springframework.org/schema/mvc
  16. http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  17. http://www.springframework.org/schema/tx
  18. http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
  19.  
  20. <!-- <mvc:default-servlet-handler />-->
  21. <mvc:resources mapping="/js/**" location="/js/"/>
  22. <mvc:annotation-driven
  23. content-negotiation-manager="contentNegotiationManager" />
  24.  
  25. <context:component-scan base-package="com.study.demo">
  26. <context:include-filter type="annotation"
  27. expression="org.springframework.stereotype.Controller" />
  28. </context:component-scan>
  29.  
  30. <bean id="stringHttpMessageConverter"
  31. class="org.springframework.http.converter.StringHttpMessageConverter">
  32. <property name="supportedMediaTypes">
  33. <list>
  34. <bean class="org.springframework.http.MediaType">
  35. <constructor-arg index="0" value="text" />
  36. <constructor-arg index="1" value="plain" />
  37. <constructor-arg index="2" value="UTF-8" />
  38. </bean>
  39. </list>
  40. </property>
  41. </bean>
  42. <bean id="mappingJacksonHttpMessageConverter"
  43. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
  44.  
  45. <bean
  46. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  47. <property name="messageConverters">
  48. <list>
  49. <ref bean="stringHttpMessageConverter" />
  50. <ref bean="mappingJacksonHttpMessageConverter" />
  51. </list>
  52. </property>
  53. </bean>
  54.  
  55. <bean id="contentNegotiationManager"
  56. class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
  57. <property name="mediaTypes">
  58. <map>
  59. <entry key="html" value="text/html" />
  60. <entry key="pdf" value="application/pdf" />
  61. <entry key="xsl" value="application/vnd.ms-excel" />
  62. <entry key="xml" value="application/xml" />
  63. <entry key="json" value="application/json" />
  64. </map>
  65. </property>
  66. <property name="defaultContentType" value="text/html" />
  67. </bean>
  68.  
  69. <bean id="viewResolver"
  70. class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  71. <property name="order" value="0" />
  72. <property name="contentNegotiationManager" ref="contentNegotiationManager" />
  73.  
  74. <property name="viewResolvers">
  75. <list>
  76. <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
  77. <bean
  78. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  79. <property name="viewClass"
  80. value="org.springframework.web.servlet.view.JstlView" />
  81. <property name="prefix" value="/WEB-INF/pages/" />
  82. <property name="suffix" value=".jsp"></property>
  83. </bean>
  84. </list>
  85. </property>
  86.  
  87. <property name="defaultViews">
  88. <list>
  89. <bean
  90. class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
  91. <property name="extractValueFromSingleKeyModel" value="true" />
  92. </bean>
  93. </list>
  94. </property>
  95. </bean>
  96.  
  97. </beans>

3. 在工程RabbitMQSpringProducer里面新建一个RabbitMQ与Spring集成发送消息控制器

  1. package com.study.demo.controller;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.core.MessageProperties;
  7. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestParam;
  12. import org.springframework.web.bind.annotation.ResponseBody;
  13.  
  14. /**
  15. *
  16. * @Description: RabbitMQ与Spring集成发送消息控制器
  17. * @author leeSmall
  18. * @date 2018年9月17日
  19. *
  20. */
  21. @Controller
  22. @RequestMapping("/rabbitmq")
  23. public class RabbitMqController {
  24.  
  25. private Logger logger = LoggerFactory.getLogger(RabbitMqController.class);
  26.  
  27. @Autowired
  28. private RabbitTemplate rabbitTemplate;
  29.  
  30. @ResponseBody
  31. @RequestMapping("/fanoutSender")
  32. public String fanoutSender(@RequestParam("message")String message){
  33. String opt="";
  34. try {
  35. String str = "Fanout,the message_"+" is : "+message;
  36. logger.info("**************************Send Message:["+str+"]");
  37. rabbitTemplate.send("fanout-exchange","",
  38. new Message(str.getBytes(),new MessageProperties()));
  39.  
  40. opt = "suc";
  41. } catch (Exception e) {
  42. opt = e.getCause().toString();
  43. }
  44. return opt;
  45. }
  46.  
  47. @ResponseBody
  48. @RequestMapping("/topicSender")
  49. public String topicSender(@RequestParam("message")String message){
  50. String opt="";
  51. try {
  52. String[] severities={"error","info","warning"};
  53. String[] modules={"email","order","user"};
  54. for(int i=0;i<severities.length;i++){
  55. for(int j=0;j<modules.length;j++){
  56. String routeKey = severities[i]+"."+modules[j];
  57. String str = "the message is [rk:"+routeKey+"]["+message+"]";
  58. rabbitTemplate.send("topic-exchange",routeKey,
  59. new Message(str.getBytes(),new MessageProperties()));
  60.  
  61. }
  62. }
  63. opt = "suc";
  64. } catch (Exception e) {
  65. opt = e.getCause().toString();
  66. }
  67. return opt;
  68. }
  69.  
  70. }

4. 在工程RabbitMQSpringProducer里面新建一个发送消息的/RabbitMQSpringProducer/src/main/webapp/index.jsp页面

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. System.out.println(path);
  5. String basePath = request.getScheme() + "://"
  6. + request.getServerName() + ":" + request.getServerPort()
  7. + path + "/";
  8. System.out.println(basePath);
  9. %>
  10.  
  11. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  12. <html>
  13. <head>
  14. <base href="<%=basePath%>">
  15.  
  16. <title>RabbitMQ Demo程序</title>
  17.  
  18. <meta http-equiv="pragma" content="no-cache">
  19. <meta http-equiv="cache-control" content="no-cache">
  20. <meta http-equiv="expires" content="0">
  21. <script type="text/javascript" src="<%--<%=basePath%>--%>js/jquery-1.11.0.min.js"></script>
  22. <style type="text/css">
  23. .h1 {
  24. margin: 0 auto;
  25. }
  26.  
  27. #producer{
  28. width: 48%;
  29. border: 1px solid blue;
  30. height: 80%;
  31. align:center;
  32. margin:0 auto;
  33. }
  34.  
  35. body{
  36. text-align :center;
  37. }
  38. div {
  39. text-align :center;
  40. }
  41. textarea{
  42. width:80%;
  43. height:100px;
  44. border:1px solid gray;
  45. }
  46. button{
  47. background-color: rgb(62, 156, 66);
  48. border: none;
  49. font-weight: bold;
  50. color: white;
  51. height:30px;
  52. }
  53. </style>
  54. <script type="text/javascript">
  55.  
  56. function send(controller){
  57. if($("#message").val()==""){
  58. $("#message").css("border","1px solid red");
  59. return;
  60. }else{
  61. $("#message").css("border","1px solid gray");
  62. }
  63. $.ajax({
  64. type: 'post',
  65. url:'<%=basePath%>rabbitmq/'+controller,
  66. dataType:'text',
  67. data:{"message":$("#message").val()},
  68. success:function(data){
  69. if(data=="suc"){
  70. $("#status").html("<font color=green>发送成功</font>");
  71. setTimeout(clear,1000);
  72. }else{
  73. $("#status").html("<font color=red>"+data+"</font>");
  74. setTimeout(clear,5000);
  75. }
  76. },
  77. error:function(data){
  78. $("#status").html("<font color=red>ERROR:"+data["status"]+","+data["statusText"]+"</font>");
  79. setTimeout(clear,5000);
  80. }
  81.  
  82. });
  83. }
  84.  
  85. function clear(){
  86. $("#status").html("");
  87. }
  88.  
  89. </script>
  90. </head>
  91.  
  92. <body>
  93. <h1>Hello RabbitMQ</h1>
  94. <div id="producer">
  95. <h2>Producer</h2>
  96. <textarea id="message"></textarea>
  97. <br>
  98. <button onclick="send('fanoutSender')">发送Fanout消息</button>
  99. <button onclick="send('topicSender')">发送Topic消息</button>
  100. <br>
  101. <span id="status"></span>
  102. </div>
  103. </body>
  104. </html>

5. 在工程RabbitMQSpringProducer里面新建/RabbitMQSpringProducer/src/main/webapp/WEB-INF/web.xml

  1. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  4. version="3.0">
  5. <display-name>RabbitMqSpringProducerDemo</display-name>
  6.  
  7. <servlet-mapping>
  8. <servlet-name>default</servlet-name>
  9. <url-pattern>*.js</url-pattern>
  10. </servlet-mapping>
  11.  
  12. <!-- Spring 编码过滤器 start -->
  13. <filter>
  14. <filter-name>characterEncoding</filter-name>
  15. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  16. <init-param>
  17. <param-name>encoding</param-name>
  18. <param-value>UTF-8</param-value>
  19. </init-param>
  20. <init-param>
  21. <param-name>forceEncoding</param-name>
  22. <param-value>true</param-value>
  23. </init-param>
  24. </filter>
  25. <filter-mapping>
  26. <filter-name>characterEncoding</filter-name>
  27. <url-pattern>/*</url-pattern>
  28. </filter-mapping>
  29. <!-- Spring 编码过滤器 End -->
  30.  
  31. <!-- Spring Application Context Listener Start -->
  32. <context-param>
  33. <param-name>contextConfigLocation</param-name>
  34. <param-value>classpath:applicationContext.xml</param-value>
  35. </context-param>
  36. <listener>
  37. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  38. </listener>
  39. <!-- Spring Application Context Listener End -->
  40.  
  41. <!-- Spring MVC Config Start -->
  42. <servlet>
  43. <servlet-name>SpringMVC</servlet-name>
  44. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  45. <init-param>
  46. <param-name>contextConfigLocation</param-name>
  47. <param-value>classpath:spring-mvc.xml</param-value>
  48. </init-param>
  49. <load-on-startup>1</load-on-startup>
  50. </servlet>
  51. <servlet-mapping>
  52. <servlet-name>SpringMVC</servlet-name>
  53. <!-- Filter all resources -->
  54. <url-pattern>/</url-pattern>
  55. </servlet-mapping>
  56. <!-- Spring MVC Config End -->
  57.  
  58. </web-app>

到此生产者服务代码编写完成!

6. 在Tomcat v8.5 8080里面启动RabbitMQSpringProducer,在浏览器输入地址http://localhost:8080/RabbitMQSpringProducer/访问

6. 在工程RabbitMQSpringConsumer里面新建三个fanout消费者

fanout消费者1:

  1. package com.study.demo.service.fanout;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.core.MessageListener;
  7. import org.springframework.stereotype.Component;
  8.  
  9. /**
  10. *
  11. * @Description: RabbitMQ与Spring集成fanout消费者
  12. * @author leeSmall
  13. * @date 2018年9月17日
  14. *
  15. */
  16. @Component
  17. public class FanoutService_H1 implements MessageListener{
  18. private Logger logger = LoggerFactory.getLogger(FanoutService_H1.class);
  19. public void onMessage(Message message) {
  20. logger.info("Get message:"+new String(message.getBody()));
  21. }
  22. }

fanout消费者2:

  1. package com.study.demo.service.fanout;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.core.MessageListener;
  7. import org.springframework.stereotype.Component;
  8.  
  9. /**
  10. *
  11. * @Description: RabbitMQ与Spring集成fanout消费者
  12. * @author leeSmall
  13. * @date 2018年9月17日
  14. *
  15. */
  16. @Component
  17. public class FanoutService_H2 implements MessageListener{
  18. private Logger logger = LoggerFactory.getLogger(FanoutService_H2.class);
  19. public void onMessage(Message message) {
  20. logger.info("Get message:"+new String(message.getBody()));
  21. }
  22. }

fanout消费者3:

  1. package com.study.demo.service.fanout;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.core.MessageListener;
  7. import org.springframework.stereotype.Component;
  8.  
  9. /**
  10. *
  11. * @Description: RabbitMQ与Spring集成fanout消费者
  12. * @author leeSmall
  13. * @date 2018年9月17日
  14. *
  15. */
  16. @Component
  17. public class FanoutService_H3 implements MessageListener{
  18. private Logger logger = LoggerFactory.getLogger(FanoutService_H3.class);
  19. public void onMessage(Message message) {
  20. logger.info("Get message:"+new String(message.getBody()));
  21. }
  22. }

7. 在工程RabbitMQSpringConsumer里面新建4个topic消费者

topic消费者1:

  1. package com.study.demo.service.topic;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.core.MessageListener;
  7. import org.springframework.stereotype.Component;
  8.  
  9. /**
  10. *
  11. * @Description: RabbitMQ与Spring集成topic消费者
  12. * @author leeSmall
  13. * @date 2018年9月17日
  14. *
  15. */
  16. @Component
  17. public class AllErrorTopicService implements MessageListener{
  18. private Logger logger = LoggerFactory.getLogger(AllErrorTopicService.class);
  19. public void onMessage(Message message) {
  20. logger.info("Get message:"+new String(message.getBody()));
  21. }
  22. }

topic消费者2:

  1. package com.study.demo.service.topic;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.core.MessageListener;
  7. import org.springframework.stereotype.Component;
  8.  
  9. /**
  10. *
  11. * @Description: RabbitMQ与Spring集成topic消费者
  12. * @author leeSmall
  13. * @date 2018年9月17日
  14. *
  15. */
  16. @Component
  17. public class AllLogTopicService implements MessageListener{
  18. private Logger logger = LoggerFactory.getLogger(AllLogTopicService.class);
  19. public void onMessage(Message message) {
  20. logger.info("Get message:"+new String(message.getBody()));
  21. }
  22. }

topic消费者3:

  1. package com.study.demo.service.topic;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.core.MessageListener;
  7. import org.springframework.stereotype.Component;
  8.  
  9. /**
  10. *
  11. * @Description: RabbitMQ与Spring集成topic消费者
  12. * @author leeSmall
  13. * @date 2018年9月17日
  14. *
  15. */
  16. @Component
  17. public class EmailAllTopicService implements MessageListener{
  18. private Logger logger = LoggerFactory.getLogger(EmailAllTopicService.class);
  19. public void onMessage(Message message) {
  20. logger.info("Get message:"+new String(message.getBody()));
  21. }
  22. }

topic消费者4:

  1. package com.study.demo.service.topic;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.amqp.core.Message;
  6. import org.springframework.amqp.core.MessageListener;
  7. import org.springframework.stereotype.Component;
  8.  
  9. /**
  10. *
  11. * @Description: RabbitMQ与Spring集成topic消费者
  12. * @author leeSmall
  13. * @date 2018年9月17日
  14. *
  15. */
  16. @Component
  17. public class EmailErrorTopicService implements MessageListener{
  18. private Logger logger = LoggerFactory.getLogger(EmailErrorTopicService.class);
  19. public void onMessage(Message message) {
  20. logger.info("Get message:"+new String(message.getBody()));
  21. }
  22. }

8. 在工程RabbitMQSpringConsumer里面新建/RabbitMQSpringConsumer/src/main/java/applicationContext.xml配置文件,在里面配置RabbitMQ相关配置和消费者监听队列

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ -->
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  12. http://www.springframework.org/schema/rabbit
  13. http://www.springframework.org/schema/rabbit/spring-rabbit-2.0.xsd">
  14.  
  15. <!-- 配置扫描路径 -->
  16. <context:component-scan base-package="com.study.demo">
  17. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  18. </context:component-scan>
  19.  
  20. <!-- rabbitMQ配置 -->
  21. <bean id="rabbitConnectionFactory"
  22. class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
  23. <constructor-arg value="127.0.0.1"/>
  24. <property name="username" value="guest"/>
  25. <property name="password" value="guest"/>
  26. <property name="channelCacheSize" value="8"/>
  27. <property name="port" value="5672"></property>
  28. </bean>
  29. <rabbit:admin connection-factory="rabbitConnectionFactory"/>
  30.  
  31. <!-- fanout交换器 begin-->
  32. <!-- 定义队列 -->
  33. <rabbit:queue name="h1_queue" durable="false"/>
  34. <rabbit:queue name="h2_queue" durable="false"/>
  35. <rabbit:queue name="h3_queue" durable="false"/>
  36.  
  37. <!-- 把需要数据的队列与交换器绑定一起 -->
  38. <rabbit:fanout-exchange name="fanout-exchange"
  39. xmlns="http://www.springframework.org/schema/rabbit"
  40. durable="false">
  41. <rabbit:bindings>
  42. <rabbit:binding queue="h1_queue"></rabbit:binding>
  43. <rabbit:binding queue="h2_queue"></rabbit:binding>
  44. <rabbit:binding queue="h3_queue"></rabbit:binding>
  45. </rabbit:bindings>
  46. </rabbit:fanout-exchange>
  47. <!-- fanout交换器 end-->
  48.  
  49. <!-- topic交换器 begin-->
  50. <!-- 定义队列 -->
  51. <rabbit:queue name="all_log_queue" durable="false"/>
  52. <rabbit:queue name="email_all_queue" durable="false"/>
  53. <rabbit:queue name="email_error_queue" durable="false"/>
  54. <rabbit:queue name="all_error_queue" durable="false"/>
  55.  
  56. <!-- 把需要数据的队列通过路由键与交换器绑定一起 -->
  57. <rabbit:topic-exchange name="topic-exchange"
  58. xmlns="http://www.springframework.org/schema/rabbit"
  59. durable="false">
  60. <rabbit:bindings>
  61. <rabbit:binding queue="all_log_queue" pattern="#"></rabbit:binding>
  62. <rabbit:binding queue="email_all_queue" pattern="*.email"></rabbit:binding>
  63. <rabbit:binding queue="email_error_queue" pattern="error.email"></rabbit:binding>
  64. <rabbit:binding queue="all_error_queue" pattern="error.*"></rabbit:binding>
  65.  
  66. </rabbit:bindings>
  67. </rabbit:topic-exchange>
  68.  
  69. <!-- topic交换器 end-->
  70.  
  71. <!--监听容器-->
  72. <rabbit:listener-container connection-factory="rabbitConnectionFactory">
  73. <rabbit:listener ref="fanoutService_H1" queues="h1_queue" method="onMessage" />
  74. <rabbit:listener ref="fanoutService_H2" queues="h2_queue" method="onMessage" />
  75. <rabbit:listener ref="fanoutService_H3" queues="h3_queue" method="onMessage" />
  76. <rabbit:listener ref="allLogTopicService" queues="all_log_queue" method="onMessage" />
  77. <rabbit:listener ref="emailAllTopicService" queues="email_all_queue" method="onMessage" />
  78. <rabbit:listener ref="emailErrorTopicService" queues="email_error_queue" method="onMessage" />
  79. <rabbit:listener ref="allErrorTopicService" queues="all_error_queue" method="onMessage" />
  80. </rabbit:listener-container>
  81.  
  82. </beans>

9. 在工程RabbitMQSpringConsumer里面新建/RabbitMQSpringConsumer/src/main/java/spring-mvc.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- 查找最新的schemaLocation 访问 http://www.springframework.org/schema/ -->
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xmlns:tx="http://www.springframework.org/schema/tx"
  8. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  9. xsi:schemaLocation="http://www.springframework.org/schema/aop
  10. http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  11. http://www.springframework.org/schema/beans
  12. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  13. http://www.springframework.org/schema/context
  14. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  15. http://www.springframework.org/schema/mvc
  16. http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  17. http://www.springframework.org/schema/tx
  18. http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
  19.  
  20. <!-- 启用MVC注解 -->
  21. <mvc:annotation-driven />
  22.  
  23. <!-- 静态资源文件,不会被Spring MVC拦截 -->
  24. <mvc:resources location="/resources/" mapping="/resources/**"/>
  25.  
  26. <!-- 指定Sping组件扫描的基本包路径 -->
  27. <context:component-scan base-package="com.study.demo" >
  28. <!-- 这里只扫描Controller,不可重复加载Service -->
  29. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  30. </context:component-scan>
  31.  
  32. <!-- JSP视图解析器-->
  33. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  34. <property name="prefix" value="/WEB-INF/views/" />
  35. <property name="suffix" value=".jsp" />
  36. <!-- 定义其解析视图的order顺序为1 -->
  37. <property name="order" value="1" />
  38. </bean>
  39.  
  40. </beans>

10. 在工程RabbitMQSpringConsumer里面新建/RabbitMQSpringConsumer/src/main/webapp/WEB-INF/web.xml配置文件

  1. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  4. version="3.0">
  5. <display-name>RabbitMqSpringConsumerDemo</display-name>
  6.  
  7. <context-param>
  8. <param-name>logbackConfigLocation</param-name>
  9. <param-value>/WEB-INF/conf/logback.xml</param-value>
  10. </context-param>
  11.  
  12. <!-- Spring 编码过滤器 start -->
  13. <filter>
  14. <filter-name>characterEncoding</filter-name>
  15. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  16. <init-param>
  17. <param-name>encoding</param-name>
  18. <param-value>UTF-8</param-value>
  19. </init-param>
  20. <init-param>
  21. <param-name>forceEncoding</param-name>
  22. <param-value>true</param-value>
  23. </init-param>
  24. </filter>
  25. <filter-mapping>
  26. <filter-name>characterEncoding</filter-name>
  27. <url-pattern>/*</url-pattern>
  28. </filter-mapping>
  29. <!-- Spring 编码过滤器 End -->
  30.  
  31. <!-- Spring Application Context Listener Start -->
  32. <context-param>
  33. <param-name>contextConfigLocation</param-name>
  34. <param-value>classpath:applicationContext.xml</param-value>
  35. </context-param>
  36. <listener>
  37. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  38. </listener>
  39. <!-- Spring Application Context Listener End -->
  40.  
  41. <!-- Spring MVC Config Start -->
  42. <servlet>
  43. <servlet-name>SpringMVC</servlet-name>
  44. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  45.  
  46. <init-param>
  47. <param-name>contextConfigLocation</param-name>
  48. <param-value>classpath:spring-mvc.xml</param-value>
  49. </init-param>
  50. <load-on-startup>1</load-on-startup>
  51. </servlet>
  52. <servlet-mapping>
  53. <servlet-name>SpringMVC</servlet-name>
  54. <!-- Filter all resources -->
  55. <url-pattern>/</url-pattern>
  56. </servlet-mapping>
  57. <!-- Spring MVC Config End -->
  58.  
  59. </web-app>

11. 生产者消费者共同日志配置文件/RabbitMQSpringConsumer/src/main/webapp/WEB-INF/conf/logback.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3.  
  4. <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  5. <encoder>
  6. <!--<Pattern>%d{HH:mm:ss.SSS} [%T] %level %logger{36} - %msg%n</Pattern>-->
  7. <Pattern>%d{yyyy/MM/dd-HH:mm:ss} %level [%thread] %caller{1} - %msg%n</Pattern>
  8. </encoder>
  9. </appender>
  10.  
  11. <logger name="com.study.demo" level="debug" addtivity="false"/>
  12. <logger name="org.springframework" level="error" addtivity="false" />
  13.  
  14. <root level="debug">
  15. <appender-ref ref="STDOUT"/>
  16. </root>
  17.  
  18. </configuration>

 到此消费端代码编写完成!

12. 在Tomcat v8.5 8081里面启动RabbitMQSpringConsumer消费者

在生产者RabbitMQSpringProducer页面发送fanout消息

查看消费者RabbitMQSpringConsumer的情况

在生产者RabbitMQSpringProducer页面发送topic消息

查看消费者RabbitMQSpringConsumer的情况

示例代码获取地址

消息中间件系列四:RabbitMQ与Spring集成的更多相关文章

  1. RabbitMQ入门教程(十六):RabbitMQ与Spring集成

    原文:RabbitMQ入门教程(十六):RabbitMQ与Spring集成 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https: ...

  2. RabbitMQ与spring集成,配置完整的生产者和消费者

    RabbitMQ与AMQP协议详解可以看看这个 http://www.cnblogs.com/frankyou/p/5283539.html 下面是rabbitMQ和spring集成的配置,我配置了二 ...

  3. RabbitMQ第四篇:Spring集成RabbitMQ

    前面几篇讲解了如何使用rabbitMq,这一篇主要讲解spring集成rabbitmq. 首先引入配置文件org.springframework.amqp,如下 <dependency> ...

  4. SSM框架开发web项目系列(五) Spring集成MyBatis

    前言 在前面的MyBatis部分内容中,我们已经可以独立的基于MyBatis构建一个数据库访问层应用,但是在实际的项目开发中,我们的程序不会这么简单,层次也更加复杂,除了这里说到的持久层,还有业务逻辑 ...

  5. RabbitMQ与Spring集成

    RabbitMQ服务端安装: https://blog.csdn.net/hzw19920329/article/details/53156015 与Spring集成 https://www.cnbl ...

  6. rabbitmq 和Spring 集成 实现(一)

    1.增加pom.xml依赖 <!--rabbitmq消息队列依赖架包--> <dependency> <groupId>org.springframework.am ...

  7. 消息队列RabbitMQ与Spring集成

    1.RabbitMQ简介 RabbitMQ是流行的开源消息队列系统,用erlang语言开发.RabbitMQ是AMQP(高级消息队列协议)的标准实现. 官网:http://www.rabbitmq.c ...

  8. shiro实战系列(十五)之Spring集成Shiro

    Shiro 的 JavaBean 兼容性使得它非常适合通过 Spring XML 或其他基于 Spring 的配置机制.Shiro 应用程序需要一个具 有单例 SecurityManager 实例的应 ...

  9. RabbitMQ ——与Spring集成及exchange的direct、topic方式实现和简单队列实现

    程序整体结构 Maven依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http: ...

随机推荐

  1. Yii2 数据搜索类 PostSearch

    数据搜索类 PostSearch /** * @Purpose : 添加 authorName 属性,使属性和搜索表单相对应 * @return array */ public function at ...

  2. 学习Struts--Chap01:了解Struts2

    学习之前的一些话: 这是我系统学习Java知识这么久以来第一次接触web框架,很不幸的是刚开始学习它就听到很多人说这个框架现在已经过时了,很多企业现在开发项目几乎不会用这个框架了,就是有用这个框架的项 ...

  3. list-循环小练习(作业已交未交)

    报错 list index out of range : 超出下标   这个错误是因为在写stus列表的时候写成了如下stus=['小花,未交'] ,但是取下标的时候取的是stus[1]:实际该列表中 ...

  4. vivox23幻彩版手机怎么设置双击息屏

    除了使用电源键来实现快速息屏方式外,我们还能通过双击屏幕的手势来息屏,下面小编就教大家vivox23幻彩版设置双击息屏的方法教程. vivox23幻彩版怎么设置双击息屏 第一步:打开vivox23幻彩 ...

  5. 认证鉴权与API权限控制在微服务架构中的设计与实现(四)

    引言: 本文系<认证鉴权与API权限控制在微服务架构中的设计与实现>系列的完结篇,前面三篇已经将认证鉴权与API权限控制的流程和主要细节讲解完.本文比较长,对这个系列进行收尾,主要内容包括 ...

  6. Zepto tap 穿透bug、解决移动端点击穿透问题

    当两个层重叠在一起时,或是有个弹窗,使用Zepto的tap事件时,点击上面的一层时会触发下面一层的事件,特别是底层如果是input框时,必“穿 透”,“google”说原因是“tap事件实际上是在冒泡 ...

  7. 专门为ADO二层升三层的咏南中间件(特种用途)

    专门为ADO二层升三层的咏南中间件(特种用途) 演示下载:链接: https://pan.baidu.com/s/1bulGBIZ6A1nkeErxIrGsGA 密码: 22dk 解压后运行ynmai ...

  8. Python3 与 C# 并发编程之~ Net篇

    NetCore并发编程 示例代码:https://github.com/lotapp/BaseCode/tree/master/netcore/4_Concurrency 先简单说下概念(其实之前也有 ...

  9. double compare 0

    因为double类型或float类型都是有精度的,其实都是取的近似值,所以有个误差.和一个很小的数比如0.00000001(1e-8)比较就是为了在这个误差范围内进行比较. 举个例子如double b ...

  10. InfluxDB服务器启动流程

    操作系统 : CentOS7.3.1611_x64 go语言版本:1.8.3 linux/amd64 InfluxDB版本:1.1.0 源码路径: github.com/influxdata/infl ...