1、依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2、rabbitmq链接配置
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: wq
password: qifeng
virtual-host: /
#开启ack
listener:
direct:
acknowledge-mode: manual
prefetch: 1 # 限制一次拉取消息的数量
simple:
acknowledge-mode: manual #采取手动应答
#concurrency: 1 # 指定最小的消费者数量
#max-concurrency: 1 #指定最大的消费者数量
retry:
enabled: true # 是否支持重试
3、生产者
- 声明交换机、队列、绑定关于
package com.wanqi.mq;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/11/19
* @Author wandaren
*/
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE_NAME = "boot_topic_exchange";
public static final String QUEUE_NAME = "boot_queue";
//交换机
@Bean("bootExchange")
public Exchange bootExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true)
.build();
}
//
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
//队列和交换机绑定关系
/*
知道哪个队列
知道哪个交换机
知道routing key
*/
@Bean
public Binding bindingQueueExchange(@Qualifier("bootQueue") Queue queue,
@Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
- 发送消息
package com.wanqi;
import com.wanqi.mq.RabbitMQConfig;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootMqProducersApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "boot.test", "boot mq hello~~~");
}
}
4、消费者
package com.wanqi.listener;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @Description TODO
* @Version 1.0.0
* @Date 2022/11/19
* @Author wandaren
*/
@Component
public class RabbitMQListener {
@RabbitListener(queues = {"boot_queue"})
public void listenerQueue(Object msg, Message message, Channel channel) {
final long deliveryTag = message.getMessageProperties().getDeliveryTag();
try {
System.out.println(msg.toString());
System.out.println(new String(message.getBody()));
// int x = 3/0;
channel.basicAck(deliveryTag, true);
} catch (Exception e) {
try {
channel.basicNack(deliveryTag, true, true);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
5、死信队列
消息成为死信的三种情况
1、队列消息长度到达限制;
2、消费者拒接消费消息,并且不重回队列;
3、原队列存在消息过期设置,消息到达超时时间未被消费;
5.1、声明交换机、队列、绑定队列
- topic模式
package com.wanqi.mq;
import org.spri