springboot使用rabbitmq代码示例
时间: 2023-02-12 15:16:52 浏览: 122
springboot整合rabbitmq的示例代码
1. 在pom.xml中添加RabbitMQ的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 在application.properties中添加RabbitMQ的连接配置:
```
spring.rabbitmq.host=your_host
spring.rabbitmq.port=your_port
spring.rabbitmq.username=your_username
spring.rabbitmq.password=your_password
```
3. 创建一个消息生产者:
```
@Component
public class RabbitSender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send(String message) {
rabbitTemplate.convertAndSend("queue", message);
}
}
```
4. 创建一个消息消费者:
```
@Component
public class RabbitReceiver {
@RabbitListener(queues = "queue")
public void process(String message) {
System.out.println("Receiver : " + message);
}
}
```
完整示例参考:https://spring.io/guides/gs/messaging-rabbitmq/
阅读全文