1. 導入依賴
<!--AMQP依賴,包含RabbitMQ--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>
發送消息
注入RabbitTemplate
@Autowired RabbitTemplate rabbitTemplate;
//隊列String queueName = "test.query";//消息String message = "hello rabbitmq";//發送消息rabbitTemplate.convertAndSend(queueName,message);
監聽接收消息
只需要在方法上添加注解即可
@RabbitListener(queues = "test.query")
@RabbitListener(queues = "test.query")void contextLoads(Object msg) {System.out.println("msg = " + msg);}
work模型
1. 多個消費者綁定同一個隊列,提升處理消息的速度
2. 同一個消息只會被同一個消費者處理
3. 通過prefetch限制一次只能消費一條消息,處理完才能處理下一條,實現能者多勞
spring:rabbitmq:host: localhostport: 5672virtual-host: /hmallusername: hmallpassword: 123listener:simple:prefetch: 1 # 每個消費者一次消費一個消息