springboot+rabbitmq集群完整的例子
时间: 2023-07-24 13:35:16 浏览: 117
springboot+rabbitmq 集成
以下是一个基于Spring Boot和RabbitMQ集群的完整示例:
1. 首先,需要在pom.xml文件中添加以下依赖项:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 然后,在application.yml文件中添加以下RabbitMQ配置:
```
spring:
rabbitmq:
addresses: server1:5672,server2:5672 # RabbitMQ集群地址
username: guest # RabbitMQ用户名
password: guest # RabbitMQ密码
virtual-host: / # RabbitMQ虚拟主机
```
3. 创建一个RabbitMQ配置类,如下所示:
```
@Configuration
public class RabbitMQConfig {
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses("server1:5672,server2:5672");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setVirtualHost("/");
return connectionFactory;
}
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
return rabbitTemplate;
}
}
```
4. 创建一个消息发送端,如下所示:
```
@Component
public class MessageSender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(String message) {
rabbitTemplate.convertAndSend("exchange", "routingKey", message);
}
}
```
5. 创建一个消息接收端,如下所示:
```
@Component
public class MessageReceiver {
@RabbitListener(queues = "queue")
public void receive(String message) {
System.out.println("Received message: " + message);
}
}
```
6. 最后,启动多个应用程序实例,并尝试发送和接收消息,以测试RabbitMQ集群是否正常工作。
注意:本示例中的exchange、routingKey和queue名称可以根据实际情况进行更改。
阅读全文