Spring Boot集成RabbitMQ接收JSON
时间: 2024-02-17 07:30:56 浏览: 259
消息
1. 添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 配置RabbitMQ连接信息
在application.yml文件中配置RabbitMQ连接信息:
```yaml
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
```
3. 创建消息监听器
创建一个类,实现MessageListener接口,并实现onMessage方法,用于接收消息:
```java
@Component
public class MessageListenerImpl implements MessageListener {
@Override
public void onMessage(Message message) {
try {
String jsonStr = new String(message.getBody(), "UTF-8");
System.out.println("Received JSON message: " + jsonStr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
```
4. 配置消息监听容器
创建一个SimpleMessageListenerContainer容器,配置监听队列和消息监听器:
```java
@Configuration
public class MessageListenerContainerConfig {
@Autowired
private MessageListenerImpl messageListener;
@Autowired
private ConnectionFactory connectionFactory;
@Value("${spring.rabbitmq.queue-name}")
private String queueName;
@Bean
public SimpleMessageListenerContainer messageListenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(queueName);
container.setMessageListener(messageListener);
return container;
}
}
```
5. 发送JSON消息
使用RabbitTemplate发送JSON消息:
```java
@RestController
public class MessageController {
@Autowired
private RabbitTemplate rabbitTemplate;
@Value("${spring.rabbitmq.queue-name}")
private String queueName;
@PostMapping("/send")
public void sendMessage(@RequestBody Map<String, Object> message) {
rabbitTemplate.convertAndSend(queueName, message);
}
}
```
以上就是Spring Boot集成RabbitMQ接收JSON消息的基本步骤。在实际应用中,可以根据需要对消息处理进行扩展。
阅读全文