Spring整合RabbitMQ
Spring整合RabbitMQ通常涉及以下步骤:
- 添加依赖:确保在项目的
pom.xml
中添加了Spring AMQP和RabbitMQ的依赖。
<dependencies>
<!-- Spring AMQP 依赖 -->
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.2.18.RELEASE</version>
</dependency>
<!-- RabbitMQ 客户端 -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.9.0</version>
</dependency>
</dependencies>
- 配置RabbitMQ连接:在Spring配置文件中配置RabbitMQ连接信息。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="connectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
<property name="host" value="localhost"/>
<property name="port" value="5672"/>
<property name="username" value="guest"/>
<property name="password" value="guest"/>
</bean>
<bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
</beans>
- 配置Queue、Exchange和Binding:在Spring配置文件中声明队列、交换器和绑定关系。
<rabbit:queue id="myQueue" name="myQueue" />
<rabbit:direct-exchange name="myExchange">
<rabbit:bindings>
<rabbit:binding queue="myQueue" key="myRoutingKey" />
</rabbit:bindings>
</rabbit:direct-exchange>
- 发送和接收消息:使用
RabbitTemplate
发送消息,并编写消息监听器处理接收到的消息。
// 发送消息
rabbitTemplate.convertAndSend("myExchange", "myRoutingKey", "Hello RabbitMQ!");
// 接收消息
@Component
public class MyMessageListener implements MessageListener {
public void onMessage(Message message) {
System.out.println("Received message: " + new String(message.getBody()));
}
}
- 配置监听器容器:在Spring配置文件中配置消息监听器容器,并指定队列和监听器。
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener ref="myMessageListener" method="onMessage"
评论已关闭