1. 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 配置
spring.application.name=rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=10000
# 设置消费端手动 ack
spring.rabbitmq.listener.simple.acknowledge-mode=manual
# 是否支持重试(重试次数默认为3次)
spring.rabbitmq.listener.simple.retry.enabled=true
3.1 点对点模式
3.1.1 工具类
public class RabbitMqUtils {
public static void basicAck(Channel channel, Message message, boolean multiple){
try {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), multiple);
} catch (IOException e) {
e.printStackTrace();
basicNack(channel, message, multiple, true);
}
}
public static void basicNack(Channel channel, Message message, boolean multiple, boolean requeue){
try {
channel.basicNack(message.getMessageProperties().getDeliveryTag(), multiple, requeue);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void basicReject(Channel channel, Message message, Boolean requeue){
try {
channel.basicReject(message.getMessageProperties().getDeliveryTag(), requeue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.1.2 生产者
@RestController
@RequestMapping("/screen/mq")
public class ProducerController {
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping("/send")
public Result send(@RequestParam String msg){
rabbitTemplate.convertAndSend("test", msg);
return new Result().toSuccess("OK");
}
}
3.1.3 消费者-手动ACK
@Component
@RabbitListener(queuesToDeclare = @Queue(value = "test"))
public class Test2Consumer {
@RabbitHandler
public void receive(String msg){
System.out.println(msg);
RabbitMqUtils.basicAck(channel, message, false);
}
}
3.2 广播模式
3.2.1 配置类
@Configuration
public class RabbitMqConfig {
@Bean
public FanoutExchange fanoutExchange(){
return new FanoutExchange("fanout_order_exchange", true, false);
}
@Bean
public Queue queue(){
return new Queue("fanout_order_queue", true);
}
@Bean
public Binding binding(){
return BindingBuilder.bind(queue()).to(fanoutExchange());
}
}
3.2.2 生产者
@RestController
@RequestMapping("/screen/mq")
public class ProducerController {
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping("/send")
public Result send(@RequestParam String msg){
rabbitTemplate.convertAndSend("fanout_order_exchange", "fanout_order_queue", msg);
return new Result().toSuccess("OK");
}
}