一般消费消息的应用会单独部署,不会和发布消息的应用部署到一起,所以本节也单独讲一下。
1.maven依赖、application.properties配置和上一节一样
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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
<description>rabbitmq 连接服务配置</description>
<context:property-placeholder ignore-unresolvable="true" location="classpath:/application.properties"/>
<rabbit:connection-factory id="rabbitConnectionFactory" host="${rabbit.host}" port="${rabbit.port}"
username="${rabbit.username}" password="${rabbit.password}"
virtual-host="${rabbit.vhost}" channel-cache-size="50"/>
<!-- 消费者 -->
<bean name="rabbitmqService" class="com.critc.service.RabbitmqService"></bean>
<rabbit:queue id="test_mq" name="test_mq" durable="true" auto-delete="false" exclusive="false" />
<!-- 配置监听 -->
<rabbit:listener-container connection-factory="rabbitConnectionFactory" acknowledge="auto" >
<rabbit:listener queues="test_mq" ref="rabbitmqService" />
</rabbit:listener-container>
</beans>
这里面定义了一个消费者和一个监听器来处理消息
3.RabbitmqService 消费类
@Service
public class RabbitmqService implements MessageListener {
public void onMessage(Message message) {
try {
String msg = new String(message.getBody(), "utf-8");
System.out.println("消息消费者 = " + msg);
} catch (Exception e) {
}
}
}
这里面需要强调一点,传到这里面的Message是一个对象,包含消息头、消息体等各种信息,需要进行一下转码,取到消息body,然后进行处理。
4.web.xml 启动加载配置
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext-rabbitmq.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
启动时加载配置,启动监听。
5.启动执行
控制台会输出消息body,后续可以处理这些消息