Rabbit基于Spring框架实现

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"/>

    <!-- spring amqp默认的是jackson 的一个插件,目的将生产者生产的数据转换为json存入消息队列 -->
    <bean id="jsonMessageConverter"  class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"></bean>

    <!-- spring template声明(作为一个代理-》也就是代理模式中的代理)-->
    <rabbit:template exchange="my-mq-exchange" id="amqpTemplate"  connection-factory="connectionFactory"  message-converter="jsonMessageConverter"/>

    <!-- 设置rabbit的管理 -->
    <rabbit:admin connection-factory="connectionFactory"/>

    <!-- queue 队列声明-->
    <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"/>


    <!-- 将队列绑定到交换路由同时与key绑定 -->
    <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">

    <!-- 配置spring的队列监听接口(创建监听处理对象) -->
    <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的管理 -->
    <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;

/**
 * 用于提供Rabbit的操作类
 * Created by Michael Zhao on 14-4-1.
 */
@Component
public class RabbitUtil {
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public RabbitUtil(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
    }

    public <T> void sendReliable(String exchange, T message) {
        //实现将message通过json转换&将对象发送
        //convertAndSend(String exchange, String routingKey, Object message, MessagePostProcessor messagePostProcessor, CorrelationData correlationData)
        rabbitTemplate.convertAndSend(exchange, "", message, new MessagePostProcessor() {
            //实现message操作处理实现
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置信息的属性信息&设置发送模式(PERSISTENT:连续的)
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return message;
            }
        }, new CorrelationData(String.valueOf(message)));
    }
}

rabbit监听接口层
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;

/**
 * 用于提供Rabbit监听接口层
 * Created by Michael Zhao on 14-4-1.
 */
@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);
    }

    /**
     * 实现将信息塞入到redis中
     * @param 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);
        }
    }
}

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();
            }
        }
    }
}

提示:如果想要运行着一些代码,请设置对应的Spring环境。对于redis的配置这边可以不设置直接去除。redis的介绍将在下一遍中涉及。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值