rabbitmq配合springboot示例
时间: 2023-10-14 14:19:50 浏览: 98
这里是一个简单的rabbitmq和springboot配合的示例:
1. 首先,我们需要在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 接下来,我们需要在application.properties中添加rabbitmq的配置:
```properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
```
3. 然后,在我们的代码中,我们可以定义一个队列和一个交换机:
```java
@Configuration
public class RabbitConfig {
public static final String QUEUE_NAME = "test.queue";
public static final String EXCHANGE_NAME = "test.exchange";
public static final String ROUTING_KEY = "test.routingKey";
@Bean
public Queue queue() {
return new Queue(QUEUE_NAME, true);
}
@Bean
public DirectExchange exchange() {
return new DirectExchange(EXCHANGE_NAME);
}
@Bean
public Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);
}
}
```
4. 然后,我们可以编写一个生产者来发送消息到队列中:
```java
@Component
public class RabbitProducer {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String message) {
amqpTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, RabbitConfig.ROUTING_KEY, message);
}
}
```
5. 最后,我们可以编写一个消费者来处理队列中的消息:
```java
@Component
@RabbitListener(queues = RabbitConfig.QUEUE_NAME)
public class RabbitConsumer {
@RabbitHandler
public void receive(String message) {
System.out.println("Received message: " + message);
}
}
```
这样,我们就完成了rabbitmq和springboot的配合示例,当我们发送一个消息到队列中时,消费者就会接收到这条消息。
阅读全文