RabbitMQ与Spirng的集成
准备工作:idea/eclipse(我使用Idea开发工具),JDK1.8,Spring4.0,Maven
创建MAVEN工程
1、创建生产者的一个简单的Maven工程,创建方式这里就不描述了,创建后的目录结构如下
在这里主要两个工程一个是Product(生产端),Consumer(消费端)。
pom文件添加依赖
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
统一配置
applicationConect.xml命名空间添加以下信息
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-2.0.xsd">
</beans>
RabbitMQ相关连接配置信息
<!-- rabbitMQ配置 -->
<bean id="rabbitConnectionFactory"
class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
<constructor-arg value="192.168.244.101"/>
<property name="username" value="kevin"/>
<property name="password" value="123456"/>
<property name="channelCacheSize" value="8"/>
<property name="port" value="5672" />
</bean>
<rabbit:admin connection-factory="rabbitConnectionFactory"/>
Product生产端配置
配置rabbitTemplate
<!-- 申明一个rabbitTemplate -->
<rabbit:template id="rabbitTemplate" connection-factory="rabbitConnectionFactory" />
交换器和队列
<!-- 申明一个direct队列 -->
<rabbit:queue name="direct_queue" durable="false" />
<!-- 申明一个direct交换器,绑定direct_queue队列 -->
<rabbit:direct-exchange name="direct_exchange" durable="false"
xmlns="http://www.springframework.org/schema/rabbit">
<bindings>
<binding queue="direct_queue" />
</bindings>
</rabbit:direct-exchange>
使用
代码里通过@Autowrite 把rabbitTemplate引入,然后通过rabbitTemplate发送消息即可。同时也可以通过MessageProperties给需要发送的消息设置属性。
Consumer消费端
消费者中也可配置队列和交换器,以及指定队列和交换器绑定的路由键
<!-- 申明一个direct队列 -->
<rabbit:queue name="direct_queue" durable="false" />
<!-- 申明一个direct交换器,绑定direct_queue队列 -->
<rabbit:direct-exchange name="direct_exchange" durable="false"
xmlns="http://www.springframework.org/schema/rabbit">
<bindings>
<binding queue="direct_queue" />
</bindings>
</rabbit:direct-exchange>
添加消费者bean
这里主要就是一个实现MessageListener或者ChannelAwareMessageListener的一个具体消费者,以下是配置信息
<!-- 定义消费者 -->
<bean id="directService" class="com.kevin.direct.DirectService" />
监听器
<!--监听容器-->
<rabbit:listener-container connection-factory="rabbitConnectionFactory">
<rabbit:listener ref="directService" queues="direct_queue" method="onMessage"/>
</rabbit:listener-container>
使用
消费者实现MessageListener接口即可