springboot 中使用 rabbitmq 简单模式 只需要几点简单配置即可;
目录
springboot 中使用 rabbitmq 简单模式 只需要几点简单配置即可;
2. 在 application.yml 中配置rabbitmq的 连接信息:
结果 :控制台打印出消费者的log日志:receiver: rabbit-mq-test
1.先加入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 在 application.yml 中配置rabbitmq的 连接信息:
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
3.队列配置,启动时创建队列
@Configuration
public class RabbitMqConfig {
@Bean
public Queue createQueue(){
return new Queue("hello-queue");
}
}
4.创建生产者
@Component
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String msg){
this.amqpTemplate.convertAndSend("hello-queue",msg);
}
}
5.创建消费者
@Component
public class Receiver {
@RabbitListener(queues = "hello-queue")
public void process(String msg){
System.out.println("receiver: "+msg);
}
}
6.测试类中测试
@SpringBootTest
class Rabbitmt1ApplicationTests {
@Autowired
private Sender sender;
@Test
void contextLoads() {
sender.send("rabbit-mq-test");
}
}