16rabllitMq在项目中的使用
生产者,当有变化的数据时,需要通知前台系统,搜索系统(消费者)
一对多
1后台系统整合spring(生产者:生产者到交换机)
1-1》导入依赖需要配置在taotao-manage-service中
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
1-2》添加配置文件
applicationContext-rabbitmq.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/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!-- 定义RabbitMQ的连接工厂 -->
<rabbit:connection-factory id="connectionFactory"
host="${rabbitmq.ip}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"
virtual-host="${rabbitmq.vhost}" />
<!-- 定义交换器,
auto-declare属性:自动声明,如果该交换机不存在则自动创建
-->
<rabbit:topic-exchange name="TT_MANAGE_ITEM_EXCHANGE" auto-declare="true" durable="true"/>
<!-- 定义Rabbit模板,指定连接工厂以及定义交换机(exchange) -->
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="TT_MANAGE_ITEM_EXCHANGE" />
<!-- MQ的管理,包括队列、交换器等 -->
<rabbit:admin connection-factory="connectionFactory" />
</beans>
rabbitmq.properties
1-3》在后台系统ItemService中发送消息
在修改商品信息时,需要作为生产者发给交换机
================================================
2前台系统
2-1》添加依赖
2-2》编写配置文件
applicationContext-rabblitmq.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/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!-- 定义RabbitMQ的连接工厂 -->
<rabbit:connection-factory id="connectionFactory"
host="${rabbitmq.ip}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"
virtual-host="${rabbitmq.vhost}" />
<!-- MQ的管理,包括队列、交换器等 -->
<rabbit:admin connection-factory="connectionFactory" />
<!-- 定义队列,自动声明 -->
<rabbit:queue name="TT_WEB_ITEM_QUEUE" auto-declare="true" durable="true"/>
<bean id="itemlistener" class="com.taotao.web.mq.ItemMqListener" />
<!-- 队列监听 -->
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener ref="itemlistener" method="getMsg" queue-names="TT_WEB_ITEM_QUEUE" />
</rabbit:listener-container>
</beans>