spring整合rabbitmq

1.RabbitMQ简介
RabbitMQ是流行的开源消息队列系统,用erlang语言开发。RabbitMQ是AMQP(高级消息队列协议)的标准实现。 

官网:http://www.rabbitmq.com/

2 spring 整合RabbitMQ pom.xml

<!--mq-->
<dependency>
	<groupId>com.rabbitmq</groupId>
	<artifactId>amqp-client</artifactId>
	<version>4.2.1</version>
</dependency>
<dependency>
	<groupId>org.springframework.amqp</groupId>
	<artifactId>spring-rabbit</artifactId>
	<version>1.7.3.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework.amqp</groupId>
	<artifactId>spring-amqp</artifactId>
	<version>1.7.3.RELEASE</version>
</dependency>
<!--mq-->

rabbitMQ.xml

<?xml version="1.0" encoding="UTF8"?>
<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" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	   http://www.springframework.org/schema/beans/spring-beans.xsd
	   http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	   http://www.springframework.org/schema/context
	   http://www.springframework.org/schema/context/spring-context-4.1.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
    <!-- 连接服务配置 -->
    <rabbit:connection-factory id="connectionFactory" host="127.0.0.1" port="5672"
                               username="test" password="test"
                               virtual-host="testmq" connection-factory="refConnectionFactory" />
    <rabbit:admin connection-factory="connectionFactory"/>

    <bean id="refConnectionFactory" class="com.rabbitmq.client.ConnectionFactory">
        <!-- 设置心跳时间,防止长时间未活动被防火墙杀死,默认600秒,单位:秒 -->
        <property name="requestedHeartbeat" value="240" />
        <!-- 连接超时时间,单位:毫秒 -->
        <property name="connectionTimeout" value="2000" />
    </bean>

    <!--申明一个消息队列Queue-->
    <!-- durable:是否持久化-->
    <!-- exclusive: 仅创建者可以使用的私有队列,断开后自动删除-->
    <!-- auto_delete: 当所有消费客户端连接断开后,是否自动删除队列-->
    <rabbit:queue id="testQueue" name="testQueue" durable="true" auto-delete="false" exclusive="false"/>

    <!--交换机定义-->
    <!--rabbit:direct-exchange:定义exchange模式为direct,意思就是消息与一个特定的路由键完全匹配,才会转发。-->
    <!--rabbit:binding:设置消息queue匹配的key -->
    <rabbit:direct-exchange id="testExchange" name="testExchange" durable="true" auto-delete="false">
        <rabbit:bindings>
            <rabbit:binding queue="testQueue" key="testQueueKey"/>
        </rabbit:bindings>
    </rabbit:direct-exchange>

    <rabbit:template id="rabbitTemplate" exchange="testExchange" connection-factory="connectionFactory" />

    <!--申明一个消息队列Queue-->
    <rabbit:queue id="TestDefaultRabbitMQDemo" name="TestDefaultRabbitMQDemo" durable="true" auto-delete="false" exclusive="false"/>

    <!--交换机定义-DefaultExchange-->
    <rabbit:template id="defaultExchangeTemplate" exchange="" connection-factory="connectionFactory" />

</beans>
单元测试MQTest.java

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class MQTest {

    @Autowired
    @Qualifier("rabbitTemplate")
    private RabbitTemplate rabbitTemplate;

    @Autowired
    @Qualifier("defaultExchangeTemplate")
    private RabbitTemplate defaultExchangeTemplate;

    /****
     * 生产
     */
    @Test
    public void Produce() {
        for (int i = 0; i < 100; i++) {
            TestRabbitMQDemo rabbitMQDemo = new TestRabbitMQDemo();
            rabbitMQDemo.setName("***testRabbitMQ***");
            String jsonMessage= toJSONString(rabbitMQDemo);
            rabbitTemplate.convertAndSend("testExchange", "testQueueKey", jsonMessage);
        }
    }

    /****
     * 生产默认DefaultExchange
     */
    @Test
    public void DefaultExchangeProduce() {
        for (int i = 0; i < 100; i++) {
            TestDefaultRabbitMQDemo rabbitMQDemo = new TestDefaultRabbitMQDemo();
            rabbitMQDemo.setName("***testRabbitMQ***");
            String jsonMessage= toJSONString(rabbitMQDemo);
            defaultExchangeTemplate.convertAndSend("TestDefaultRabbitMQDemo", jsonMessage);
        }
    }

    /****
     * 消费
     */
    @Test
    public void testConsumerRabbitMQ() {
        String QueueName="testQueue";
//      String QueueName="TestDefaultRabbitMQDemo";
        TestRabbitMQDemo TestRabbitMQDemo = getMessage(QueueName, TestRabbitMQDemo.class);
        System.err.println("getName()===" + TestRabbitMQDemo.getName());
    }

    /****
     * 消费消息     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getMessage(String queueName, Class<T> clazz) {
        Message message = rabbitTemplate.receive(queueName, 5000);
        T value = JSON.parseObject(message.getBody(), clazz, Feature.UseBigDecimal);
//      T value = JSONObject.parseObject(message.getBody(), clazz);
        return value;
    }

    /****
     * 转化JSONString
     * @param obj
     * @return
     */
    private String toJSONString(Object obj){
        String jsonMessage = JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.SkipTransientField);
        return jsonMessage;
    }
}
java对象

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class TestDefaultRabbitMQDemo {
    private String name;
    private String time;
}

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class TestRabbitMQDemo {
    private String name;
    private String time;
}

以上是代码会自动创建Exchange、Queue、routekey。

下面是通过控制台添加Exchange、Queue、绑定关系bindings、设置routekey






exchanges, queues, and bindings是三个基础的概念, 他们的作用是:exchanges are where producers publish their messages, queues are where the messages end up and are received by consumers, and bindings are how the messages get routed from the exchange to particular queues. 

获得消息的个数

@Autowired
    private ConnectionFactory connectionFactory;
    
    @Test
    public void testQueueNameCount() throws IOException {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        Object messageCount = rabbitAdmin.getQueueProperties("queueName").get(RabbitAdmin.QUEUE_MESSAGE_COUNT);
        System.err.println(messageCount);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值