一般消費消息的應用會單獨部署,不會和發布消息的應用部署到一起,所以本節也單獨講一下。
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.啟動執行
rabbitmq監聽.png
控制臺會輸出消息body,后續可以處理這些消息