当前位置:   article > 正文

天易48----Springmvc结合rabbitmq简单示例_springmvc rabbitmq routingkey

springmvc rabbitmq routingkey

一:rabbitmq的服务安装步骤这里就省略了,网上参考教程很多,在开发之前需要导入一下rabbitmq与Spring的依赖包:


如果是maven架构,可以在pom.xml文件中添加如下配置:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>4.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.amqp</groupId>
    <artifactId>spring-rabbit</artifactId>
    <version>1.4.5.RELEASE</version>
</dependency>

在加载的文件中需导入rabbitmq的发送端与接收端配置(我这里是在application-context.xml配置文件中引进也可直接在web.xml中直接引进),如下:

application-context.xml文件中引进,web.xml文件中已经引进加载application-context.xml配置

<import resource="application-rabbitProduce.xml"/>
<import resource="application-rabbitConsume.xml"/>

或在web.xml文件中,如下图中箭头指向方向的位置添加引进上述两个文件:



二:rabbitmq发送端代码:

1)发送端application-rabbitProduce.xml配置文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  10. http://www.springframework.org/schema/rabbit
  11. http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd">
  12. <!-- 定义连接工厂,用于创建连接等 -->
  13. <rabbit:connection-factory id="connectionFactory" username="ty" password="ty" host="192.168.120.154" port="5672"/>
  14. <!-- 定义admin,producer中的exchange,queue会自动的利用该admin自动在spring中生成 -->
  15. <rabbit:admin connection-factory="connectionFactory"/>
  16. <!-- 定义rabbitmq模板,用于接收以及发送消息 -->
  17. <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="hjexchange" routing-key="wzh"/>
  18. <!-- 利用admin来定义队列,spring会自动根据下面的定义创建队列
  19. 队列名 是否持久化 是否是排他队列 不使用的时候是否删除 -->
  20. <rabbit:queue name="com.ty.test" auto-delete="false" durable="true" exclusive="false" auto-declare="true"/>
  21. <!-- 定义Exchange,并且将队列与Exchange绑定,设定Routing Key -->
  22. <!-- name为Echange的name -->
  23. <rabbit:direct-exchange name="hjexchange" durable="true" auto-delete="false">
  24. <rabbit:bindings>
  25. <rabbit:binding key="com.ty.test" queue="com.ty.test"></rabbit:binding>
  26. </rabbit:bindings>
  27. </rabbit:direct-exchange>
  28. </beans>
2)发送端controller类,这里我用了get方式接收,实际应用中用post方式:

  1. package com.jy.app.controller.mobile.rabbitmq;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import javax.annotation.Resource;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11. import com.jy.app.controller.mobile.aop.User;
  12. @Controller
  13. @RequestMapping("/rabbitmq")
  14. public class RabbitmqController {
  15. @Resource
  16. private MessageProducer messageProducer;
  17. @RequestMapping(value="/rabbitmqSend",method = RequestMethod.GET)
  18. @ResponseBody
  19. public Map<String,Object> rabbitmqSend(HttpServletRequest request,HttpServletResponse response,
  20. User user,String name){
  21. String message = name;
  22. Map<String,Object> map=new HashMap<String,Object>();
  23. map.put("info", message);
  24. messageProducer.send(message);
  25. return map;
  26. }
  27. }
3)MessageProducer

  1. package com.jy.app.controller.mobile.rabbitmq;
  2. import javax.annotation.Resource;
  3. import org.apache.log4j.Logger;
  4. import org.springframework.amqp.core.AmqpTemplate;
  5. import org.springframework.stereotype.Service;
  6. import com.google.gson.Gson;
  7. import com.jy.app.controller.mobile.aop.User;
  8. /**
  9. * 通过调用rabbitmq AmqpTemplate对象发送消息
  10. * @author Administrator
  11. *
  12. */
  13. @Service
  14. public class MessageProducer {
  15. private Logger log = Logger.getLogger(MessageProducer.class);
  16. @Resource
  17. private AmqpTemplate amqpTemplate;
  18. public void send(Object message) {
  19. log.info("发送消息为 : " + message);
  20. Gson gson=new Gson();
  21. User user=new User();
  22. user.setName("ty");
  23. user.setAge("27");
  24. amqpTemplate.convertAndSend("com.ty.test", gson.toJson(user));
  25. }
  26. }
4)在没有引进rabbitmq接收文件时,页面输入访问地址:http://localhost:8082/StanClaimProd-app/rabbitmq/rabbitmqSend?name=wzh,输入如下地址:http://localhost:15672(输入登录名和密码)查看rabbitmq页面端,效果图如下:(可以看出队列中已有一条数据)


三:rabbitmq接收端代码:

1)接收端application-rabbitConsume.xml文件代码:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  10. http://www.springframework.org/schema/rabbit
  11. http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd">
  12. <!-- 定义连接工厂,用于创建连接等 -->
  13. <rabbit:connection-factory id="connectionFactory" username="ty" password="ty" host="192.168.120.154" port="5672"/>
  14. <!-- 定义admin,producer中的exchange,queue会自动的利用该admin自动在spring中生成 -->
  15. <rabbit:admin connection-factory="connectionFactory"/>
  16. <!-- 利用admin来定义队列,spring会自动根据下面的定义创建队列
  17. 队列名 是否持久化 是否是排他队列 不使用的时候是否删除 -->
  18. <rabbit:queue name="com.ty.test" auto-delete="false" durable="true" exclusive="false" auto-declare="true"/>
  19. <!-- 定义Exchange,并且将队列与Exchange绑定,设定Routing Key -->
  20. <!-- name为Echange的name -->
  21. <rabbit:direct-exchange name="hjexchange" durable="true" auto-delete="false">
  22. <rabbit:bindings>
  23. <rabbit:binding key="com.ty.test" queue="com.ty.test"></rabbit:binding>
  24. </rabbit:bindings>
  25. </rabbit:direct-exchange>
  26. <!-- 定义消费者,消费消息 -->
  27. <bean id="directConsumer" class="com.jy.app.controller.mobile.rabbitmq.DirectConsumer"></bean>
  28. <!--开启监听,也可以理解为:
  29. 将消费者与队列进行绑定,这样就会在,当队列有消息的时候,会由绑定的消费者来进行消费,
  30. 也可以算是指定消费者来监听指定的队列.当有消息到达的时候,通知消费者进行消费 -->
  31. <rabbit:listener-container connection-factory="connectionFactory">
  32. <!-- 注入bean,指定队列 -->
  33. <rabbit:listener ref="directConsumer" queues="com.ty.test"/>
  34. </rabbit:listener-container>
  35. </beans>
2)接收端代码,该类实现rabbitmq MessageListener接口:

  1. package com.jy.app.controller.mobile.rabbitmq;
  2. import java.io.UnsupportedEncodingException;
  3. import org.apache.log4j.Logger;
  4. import org.springframework.amqp.core.Message;
  5. import org.springframework.amqp.core.MessageListener;
  6. import org.springframework.stereotype.Service;
  7. import com.google.gson.Gson;
  8. import com.jy.app.controller.mobile.aop.User;
  9. /**
  10. * rabbitmq接收推送的数据
  11. * @author Administrator
  12. *
  13. */
  14. @Service
  15. public class DirectConsumer implements MessageListener {
  16. private Logger log = Logger.getLogger(DirectConsumer.class);
  17. public DirectConsumer(){
  18. log.info("===DirectConsumer====");
  19. }
  20. @Override
  21. public void onMessage(Message message) {
  22. // TODO Auto-generated method stub
  23. Gson gson=new Gson();
  24. log.info("------> DirectConsumer 接收到的消息为 : " + message);
  25. try {
  26. log.info("===endDat===="+ new String(message.getBody(),"UTF-8"));
  27. String data=new String(message.getBody(),"UTF-8");
  28. User user=gson.fromJson(data, User.class);
  29. log.info("===endDat===="+user.getAge()+"====="+user.getName());
  30. } catch (Exception e) {
  31. // TODO Auto-generated catch block
  32. e.printStackTrace();
  33. }
  34. }
  35. }
3)将之前注释掉的接收端配置文件代码放开后,再执行http://localhost:8082/StanClaimProd-app/rabbitmq/rabbitmqSend?name=wzh,输入如下地址:http://localhost:15672(输入登录名和密码)查看rabbitmq页面端,效果图如下(图中的队列信息已经被取出):
3)后台队列获取数据打印的log日志如下:

2017-08-07 15:59:11,423 INFO  - 发送消息为 : wzh
2017-08-07 15:59:11,482 INFO  - ------> DirectConsumer 接收到的消息为 : (Body:'{"name":"ty","age":"27"}'MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=null, replyTo=null, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=hjexchange, receivedRoutingKey=com.ty.test, deliveryTag=1, messageCount=0])
2017-08-07 15:59:11,483 INFO  - ===endDat===={"name":"ty","age":"27"}
2017-08-07 15:59:11,488 INFO  - ===endDat====27=====ty



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/139192
推荐阅读
相关标签
  

闽ICP备14008679号