一、引入依赖
1、在pom.xml文件中引入rabbitMq依赖--
<!--引入rabbitMQ的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>java
2、配置application.yml中
rabbitmq:
host: 自己的ip
publisher-confirm-type: correlated #开启异步消息确认
publisher-returns: true #开启publisher-return的机制
template:
mandatory: true #消息路由失败,调用ReturnCallback
listener:
simple:
retry:
enabled: true # 开启消费者失败重试
initial-interval: 1000 # 初识的失败等待时长为1秒
multiplier: 1 # 失败的等待时长倍数,下次等待时长 = multiplier * last-interval
max-attempts: 3 # 最大重试次数
stateless: true # true无状态;false有状态。如果业务中包含事务,这里改为false
二、创建一个配置类,使用 (@Configuration)
使用@Autowried注解,自动注入RabbitTemplate 对象
@Autowried
RabbitTemplate rabbitTemplate
创建队列,设置消息持久化,保证消息不丢失
@Bean
public Queue newQueue(){
return new Queue("消息队列的队列名",true); //true的作用设置消息持久化,保证消息不丢失
}
设置RabbitMq回调函数,保证消息不丢失(消息发送失败后重新发送)
@PostConstruct
public void init(){
System.out.println("消息队列初始化");
rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback(){
@override
public void returnMessage(Message message, int replyCode, String replyText, String exchange, String routingKey){
//获取消息
String msg=new String(message.getBody);
//重新发送,将消息发送到指定的交换机 exchange,
//会自动将消息进行序列化,并根据配置的消息转换器将消息转换为可发送的格式,然后通过 RabbitMQ 的连接通道将消息发送到指定的交换机。
rabbittemplate.convertAndSend(exchange,msg);
}
})
}
三、后端业务发送消息,
//最好是将要发送的对象信息,转化成字符串的形式
String msg= JSON.toJSONString(对象);
//设置唯一标识,存入redis,证明这条消息存在
//发送消息
rabbittemplate.convertAndSend("消息队列的队列名",msg);
四、消息的接收使用使用@RabbitListener 注解
@RabbitListener(queue="消息队列的队列名")
//message 接收的消息
//channel 消息通道,可以执行一些与消息相关的操作,如确认消息、拒绝消息、重新投递消息等
public void receiveInfo(Message message, Channel channel){
try{
//获取message信息
String s = new String(message.getBody());
//将信息转化成对象
对象 = JSON.parseObject(s, 类型反射.class);
//获取唯一标识,查看消息,是否已经被接收
Boolean flag = stringRedisTemplate.hasKey(key);
if(flag){
//flag为true的时,消息没有被消费,
进行业务操作,同时根据唯一标识删除redis中的记录
//同时,确认接收mq消息
channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
return;
}
//flag=false时,证明消息已经被消费过了,确认接收消息,不在进行操作,
channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
}catch(IOException e){
throw new RuntimeException(e);
}
}