springboot+rabbitmq集群+controller
时间: 2023-07-08 10:42:57 浏览: 142
Springboot+rabbitmq集成
以下是一个基于Spring Boot、RabbitMQ集群和Controller的完整示例:
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. 创建一个Controller,如下所示:
```
@RestController
public class MessageController {
@Autowired
private MessageSender messageSender;
@PostMapping("/message")
public void sendMessage(@RequestBody String message) {
messageSender.send(message);
}
}
```
7. 最后,启动多个应用程序实例,并通过发送POST请求来测试Controller和RabbitMQ集群是否正常工作。
注意:本示例中的exchange、routingKey和queue名称可以根据实际情况进行更改。
阅读全文