Spring整合RabbitM

本文介绍了如何将Spring与RabbitMQ进行整合,包括RabbitMQ和Erlang的版本,Maven依赖注意事项,以及Spring的配置文件如`applicationContext.xml`、`application.properties`和`applicationContext-rabbit.xml`的配置内容。文中还详细讲解了消费者的自动监听和生产者的测试用例,演示了`amqpTemplate.send`和`amqpTemplate.convertAndSend`两种发送消息的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版本说明

RabbitMQ 3.5.0, Erlang 19.3

Maven依赖说明

            <dependency>
                <groupId>org.springframework.amqp</groupId>
                <artifactId>spring-rabbit</artifactId>
                <version>1.7.5RELEASE</version>
            </dependency>

1.7.5版本是用的比较多比较成熟的版本,在依赖spring-rabbit包时请注意一个细节:
在这里插入图片描述
在maven仓库中会列出此spring-rabbit对应的amqp-client和springframework包的版本,在使用时一定要把其他的包版本对应上,不然会报例如ClassNotFind之类的异常

Spring配置

applicationContext.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd"
       default-lazy-init="false">

    <!--注解-->
    <context:annotation-config />

    <context:component-scan base-package="com.lyn.rabbitmq" />

    <!--读取配置文件-->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath*:/application.properties</value>
            </list>
        </property>
    </bean>

    <import resource="applicationContext-rabbit.xml"/>
</beans>

application.properties

rabbit.host=192.168.189.131
rabbit.port=5672
rabbit.username=root
rabbit.password=root
rabbit.timeout=20000
rabbit.vhost=/

applicationContext-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.0.xsd
     http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/rabbit
     http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
    <!--自定义connectionFactory-->
    <bean id="customFactory" class="com.rabbitmq.client.ConnectionFactory">
        <property name="handshakeTimeout" value="${rabbit.timeout}"></property>
    </bean>

    <!-- 连接connectionFactory-->
    <rabbit:connection-factory  id="connectionFactory"
                                host="${rabbit.host}"
                                port="${rabbit.port}"
                                username="${rabbit.username}"
                                password="${rabbit.password}"
                                virtual-host="${rabbit.vhost}"
                                connection-factory="customFactory"
                                />

    <!--rabbitTemplate用于数据的接收和传输-->
    <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" />

    <!--当前producer中的exchange和queue会在rabbitmq服务器里自动生成-->
    <rabbit:admin connection-factory="connectionFactory" />
    <!--定义queue-->
    <rabbit:queue id="springDiQueue" name="springDiQueue"  durable="true" auto-delete="false" exclusive="false" />

    <rabbit:queue id="springFanQueue"  name="springFanQueue"  durable="true" auto-delete="false" exclusive="false" />


    <!--定义direct交换器-->
    <rabbit:direct-exchange name="springExchange" auto-delete="false" durable="true"  >
        <rabbit:bindings>
            <rabbit:binding queue="springDiQueue" key="ss"  />
        </rabbit:bindings>
    </rabbit:direct-exchange>

    <!--定义fanout交换器-->
    <rabbit:fanout-exchange name="springFanOutExchange" auto-delete="false" durable="true">
        <rabbit:bindings>
            <rabbit:binding queue="springFanQueue"></rabbit:binding>
        </rabbit:bindings>
    </rabbit:fanout-exchange>

    <!--消息接收-->
    <bean id="messageReceiver" class="com.lyn.rabbitmq.consumer.MessageConsumer"/>

    <!--自动监听 有消息到达时会通知监听在对应的队列上的监听对象-->
    <rabbit:listener-container connection-factory="connectionFactory">
        <rabbit:listener ref="messageReceiver" queues="springDiQueue"/>
    </rabbit:listener-container>
</beans>

xml使用了自定义ConnectionFactory,默认的spring-rabbit会使用包装的CachingConnectionFactory,里面没有 handshakeTimeout属性的设值,因为本人用虚拟机安装RabbitMq,有一定的网络延迟,不设置handshakeTimeout会在发送信息时出现异常,所以使用原生ConnectionFactory

org.springframework.amqp.AmqpTimeoutException: java.util.concurrent.TimeoutException
	at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:74)
	at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:379)
	at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:573)
	at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1430)
	at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1411)
	at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1387)
	at org.springframework.amqp.rabbit.core.RabbitAdmin.getQueueProperties(RabbitAdmin.java:336)
	at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.redeclareElementsIfNecessary(SimpleMessageListenerContainer.java:1209)
	at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1470)
	at java.lang.Thread.run(Thread.java:745)

代码测试

消费者

Spring配置中已经设置自动监听,有消息在指定队列中时会自动接收消息

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class MessageConsumer implements MessageListener{

    @Override
    public void onMessage(Message message) {
        System.out.println("我收到了一条信息:"+message);
    }
}

生产者

一个简单的测试用例

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")

public class RabbitMqTest extends AbstractJUnit4SpringContextTests {
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Test
    public void sendMessage() throws UnsupportedEncodingException {
        Map<String, Object> log = new HashMap<String, Object>();
        log.put("level", "info");
        log.put("timestamp", new Date());
        log.put("operateId", 1);
        log.put("msg", "铸剑山庄6阶剑法->巨阀千钧剑!");
        Message message = MessageBuilder.withBody("foo".getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setMessageId("123")
                .setHeader("bar", "baz")
                .build();
        amqpTemplate.send("springExchange","ss", message);
        amqpTemplate.convertAndSend("springExchange","ss", log);
    }
}

Api中使用使用两种不同方式发送信息
amqpTemplate.send从Spring-Rabbit版本1.3开始,它提供了MessageBuilder 和 MessagePropertiesBuilder两个类,这可以方便我们以fluent流式的方式创建Message及MessageProperties对象。
amqpTemplate.convertAndSend是另一种形式的发送,在内部使用convertMessageIfNecessary(object)产生Message对象调用send方式

结果展示

十月 29, 2018 11:06:23 上午 org.springframework.amqp.rabbit.connection.CachingConnectionFactory createBareConnection
信息: Created new connection: connectionFactory#1139bd0:0/SimpleConnection@8bf27f [delegate=amqp://root@192.168.189.131:5672/, localPort= 6497]
我收到了一条信息:(Body:'foo' MessageProperties [headers={bar=baz}, timestamp=null, messageId=123, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=text/plain, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=springExchange, receivedRoutingKey=ss, receivedDelay=null, deliveryTag=1, messageCount=0, consumerTag=amq.ctag-GKrORdJJiHPXDf9B3PLYmw, consumerQueue=springDiQueue])
我收到了一条信息:(Body:'{msg=铸剑山庄6阶剑法->巨阀千钧剑!, level=info, operateId=1, timestamp=Mon Oct 29 11:06:23 CST 2018}' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/x-java-serialized-object, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=springExchange, receivedRoutingKey=ss, receivedDelay=null, deliveryTag=2, messageCount=0, consumerTag=amq.ctag-GKrORdJJiHPXDf9B3PLYmw, consumerQueue=springDiQueue])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值