Rabbit基于Spring框架实现
来源:互联网 发布:unity3d minecraft 编辑:程序博客网 时间:2024/05/21 11:05
RabbitMq
消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。其中较为成熟的MQ产品有IBM WEBSPHERE MQ。
RabbitMQ的结构图如下:
RabbitMQ一般的使用场景:
1.作为一种事件绑定监听处理,当client触发了某一个exchange,然后rabbitMq会将取得的数据塞入到queue中。然后由于在配置文件中已经配置好了对于queue的监听接口,当有数据塞入到queue中会触发接口执行程序。
2.一般这种服务也可以作为一种延时处理的操作结合redis,将监听queue的接口绑定到redis中,可以将触发得到的数据保存到redis中然后在通过线程有后台监听数据对象。
Rabbit 数据生产者XML配置文件
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- 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/rabbit
- http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
-
- <bean id="rabbitUtil" class="com.rabbit.util.RabbitUtil"/>
-
-
- <rabbit:connection-factory id="connectionFactory" addresses="127.0.0.1:5672" publisher-confirms="true"/>
-
-
- <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"></bean>
-
-
- <rabbit:template exchange="my-mq-exchange" id="amqpTemplate" connection-factory="connectionFactory" message-converter="jsonMessageConverter"/>
-
-
- <rabbit:admin connection-factory="connectionFactory"/>
-
-
- <rabbit:queue id="queue_one" durable="true" auto-delete="false" exclusive="false" name="queue_one"/>
- <rabbit:queue id="queue_tow" durable="true" auto-delete="false" exclusive="false" name="queue_tow"/>
- <rabbit:queue id="queue_three" durable="true" auto-delete="false" exclusive="false" name="queue_three"/>
-
-
-
- <rabbit:fanout-exchange name="my-mq-exchange" durable="true" auto-delete="false" id="my-mq-exchange">
- <rabbit:bindings>
- <rabbit:binding queue="queue_one"/>
- <rabbit:binding queue="queue_tow"/>
- </rabbit:bindings>
- </rabbit:fanout-exchange>
-
-
- <rabbit:fanout-exchange name="mq-exchange2" durable="true" auto-delete="false" id="mq-exchange2">
- <rabbit:bindings>
- <rabbit:binding queue="queue_one"/>
- <rabbit:binding queue="queue_tow"/>
- <rabbit:binding queue="queue_three"/>
- </rabbit:bindings>
- </rabbit:fanout-exchange>
- </beans>
Rabbit 事件监听XML配置
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
- http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
-
-
- <bean id="consumeMessage" class="com.rabbit.test.QueueOneListener" />
-
-
- <rabbit:connection-factory id="connectionFactory" host="127.0.0.1" port="5672" username="guest" password="guest"/>
-
- <bean id="jacksonConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"/>
-
-
- <rabbit:admin connection-factory="connectionFactory"/>
-
-
- <rabbit:listener-container connection-factory="connectionFactory" message-converter="jacksonConverter" acknowledge="none">
- <rabbit:listener ref="consumeMessage" method="listenOne" queue-names="queue_one" />
- <rabbit:listener ref="consumeMessage" method="listenTwo" queue-names="queue_tow" />
- <rabbit:listener ref="consumeMessage" method="listenThree" queue-names="queue_three" />
- <rabbit:listener ref="consumeMessage" method="listenThree1" queue-names="queue_three" />
- <rabbit:listener ref="consumeMessage" method="testRedisAnnotation" queue-names="queue_three" />
- </rabbit:listener-container>
-
- </beans>
通过配置rabbit:listener来设置对于某个queue的监听方法的处理设置
封装一个Rabbit实例
- package com.rabbit.util;
-
- import org.springframework.amqp.AmqpException;
- import org.springframework.amqp.core.Message;
- import org.springframework.amqp.core.MessageDeliveryMode;
- import org.springframework.amqp.core.MessagePostProcessor;
- import org.springframework.amqp.rabbit.core.RabbitTemplate;
- import org.springframework.amqp.rabbit.support.CorrelationData;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
-
-
-
-
-
- @Component
- public class RabbitUtil {
- private final RabbitTemplate rabbitTemplate;
-
- @Autowired
- public RabbitUtil(RabbitTemplate rabbitTemplate){
- this.rabbitTemplate = rabbitTemplate;
- }
-
- public <T> void sendReliable(String exchange, T message) {
-
-
- rabbitTemplate.convertAndSend(exchange, "", message, new MessagePostProcessor() {
-
- @Override
- public Message postProcessMessage(Message message) throws AmqpException {
-
- message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
- return message;
- }
- }, new CorrelationData(String.valueOf(message)));
- }
- }
rabbit监听接口层- <span style="font-size:14px;">package com.rabbit.test;
-
- import com.rabbit.ActionInterface.RedisNoResultAction;
- import com.rabbit.annotation.RedisLock;
- import com.rabbit.util.RedisKeys;
- import com.rabbit.util.RedisLockExecute;
- import com.rabbit.util.RedisLockModel;
- import com.rabbit.util.RedisTemplate;
- import org.junit.Before;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import redis.clients.jedis.Jedis;
-
- import java.util.concurrent.TimeUnit;
-
-
-
-
-
- @Component
- public class QueueOneListener{
- @Autowired
- private RedisTemplate redisTemplate;
-
- private static final Logger log = LoggerFactory.getLogger(QueueOneListener.class);
-
- @Before
- public void setUp(){
-
- RedisLockExecute.destructionLocks(redisTemplate);
- }
-
- public void listenOne(Object foo) {
- System.out.println("listen1");
- System.out.println(foo);
- }
-
- public void listenTwo(Object foo) {
- System.out.println("listen2");
- System.out.println(foo);
- }
-
- public void listenThree(Object foo) {
- System.out.println("listen3");
- System.out.println(foo);
- }
-
- public void listenThree1(Object foo){
- System.out.println("listenThree->"+foo);
- }
-
-
-
-
-
- public void sendRedis(final Object foo){
-
- RedisLockModel redisLockModel = RedisLockExecute.acquireLock(redisTemplate, RedisKeys.REDIS_TEST, 1000, (int) TimeUnit.SECONDS.toSeconds(10));
-
- try{
- if(RedisLockExecute.ACQUIRE_RESULT(redisLockModel)){
- redisTemplate.execute(new RedisNoResultAction() {
- @Override
- public void actionNoResult(Jedis jedis) {
- jedis.lpush("sendRedis:" , foo.toString());
- }
- });
- }else{
- log.debug("acquire lock is failed!");
- }
- } catch (Exception e){
- log.error("send Redis failed , error={}", e);
- }finally {
-
- RedisLockExecute.releaseLock(redisTemplate, redisLockModel);
- }
- }
-
- @RedisLock(redisKeys = RedisKeys.REDIS_TEST , maxWait = 10, expiredTime = 1000)
- public void testRedisAnnotation(final Object foo){
- try{
- redisTemplate.execute(new RedisNoResultAction() {
- @Override
- public void actionNoResult(Jedis jedis) {
- jedis.lpush("sendRedis:" , foo.toString());
- }
- });
- } catch (Exception e){
- log.error("send Redis failed , error={}", e);
- }
- }
- }</span>
rabbit测试类
- package com.rabbit.test;
-
- import com.rabbit.util.RabbitUtil;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = {
- "classpath:/spring/root-context.xml",
- "classpath:/spring/rabbit-product.xml",
- "classpath:/spring/rabbit-context.xml",
- "classpath:/spring/redis-context.xml"
- })
- public class RabbitTest {
- @Autowired
- private RabbitUtil rabbitUtil;
-
- private Integer number = 1;
-
- @Test
- public void testRabbit() {
- while(true){
- rabbitUtil.sendReliable("my-mq-exchange", number++);
- rabbitUtil.sendReliable("mq-exchange2", number++);
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }