spring rabbitmq代码
时间: 2023-11-23 10:03:07 浏览: 64
以下是一个简单的Spring Boot应用程序中使用RabbitMQ的示例代码:
1. 首先,我们需要在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 然后,在application.properties文件中添加RabbitMQ连接信息:
```
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=username
spring.rabbitmq.password=password
```
3. 创建一个消息接收器:
```java
@Component
public class Receiver {
@RabbitListener(queues = "myqueue")
public void receiveMessage(String message) {
System.out.println("Received: " + message);
}
}
```
4. 创建一个发送者:
```java
@Component
public class Sender {
private final RabbitTemplate rabbitTemplate;
public Sender(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("myexchange", "myroutingkey", message);
}
}
```
5. 在应用程序主类中,使用@EnableRabbit注解启用RabbitMQ:
```java
@SpringBootApplication
@EnableRabbit
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
6. 最后,我们可以在任何需要发送消息的地方使用Sender类:
```java
@Autowired
private Sender sender;
// send a message
sender.sendMessage("Hello, RabbitMQ!");
```
这是一个非常简单的示例,但它演示了如何在Spring Boot中使用RabbitMQ。
阅读全文