之前写过按照官方文档学习使用RabbitMQ,了解了大概之后,我们可以开始尝试在项目里使用它。
1.前提准备
RabbitMQ,可以搭建在linux环境和windows环境。安装比较简单,这边先不赘述了。以后补上。
我们要引入jar包,给出maven
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
版本自行选择。
开一个项目,这里是使用xml去配置。
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"
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">
<description>Spring公共配置</description>
<!-- 扫描注解 -->
<context:component-scan base-package="com.george"/>
<context:annotation-config/>
<!-- mq服务 生产者配置 -->
<import resource="classpath:context/applicationContext-producer-mq.xml"/>
<!-- mq服务 消费者配置 -->
<import resource="classpath:context/applicationContext-consumer-mq.xml"/>
</beans>
准备一下properties文件,消费者和生产者都需要!
mq.properties
#参数
mq.host = 主机ip
mq.username = 用户名
mq.password = 密码
mq.port = 5672
mq.vhost = /
#消息确认
mq.publisher-confirms = true
#缓存数量,默认25
mq.channel-cache-size = 50
1.生产者
我们现在先安排生产者:
在业务代码中,我们一般都期望这种调用能够尽可能的简便。所以最好的情况就是通过注入和设置参数我们可以直接发送消息。
applicationContext-producer-mq.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 消息对象json转换类 -->
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />
<!-- 配置文件位置 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath*:mq.properties" ignore-resource-not-found="true"/>
<!-- 连接工厂配置 -->
<rabbit:connection-factory id="connectionFactory"