1. 备份交换机
备份交换机可以理解为 RabbitMQ 中交换机的“备胎”,当我们为某一个交换机声明一个对应的备份交换机时,就是为它创建一个备胎,当交换机接收到一条不可路由消息时,将会把这条消息转发到备份交换机中,由备份交换机来进行转发和处理,通常备份交换机的类型为 Fanout ,这样就能把所有消息都投递到与其绑定的队列中,然后我们在备份交换机下绑定一个队列,这样所有那些原交换机无法被路由的消息,就会都进 入这个队列了。当然,我们还可以建立一个报警队列,用独立的消费者来进行监测和报警。
2.修改配置类
//备份交换机public static final String BACKUP_EXCHANGE_NAME = "backup.exchange";//备份队列public static final String BACKUP_QUEUE_NAME = "backup.queue";//告警队列public static final String WARNING_QUEUE_NAME = "warning.queue";@Bean("backupExchange")public FanoutExchange backupExchange() {return new FanoutExchange(BACKUP_EXCHANGE_NAME);}// 声明确认队列@Bean("backupQueue")public Queue backupQueue() {return QueueBuilder.durable(BACKUP_QUEUE_NAME).build();}@Bean("warningQueue")public Queue warningQueue() {return QueueBuilder.durable(WARNING_QUEUE_NAME).build();}@Beanpublic Binding backupQueueBindingBackupQueue(@Qualifier("backupQueue") Queue backupQueue,@Qualifier("backupExchange") FanoutExchange backupExchange) {return BindingBuilder.bind(backupQueue).to(backupExchange);}@Beanpublic Binding warningQueueBindingBackupQueue(@Qualifier("warningQueue") Queue warningQueue,@Qualifier("backupExchange") FanoutExchange backupExchange) {return BindingBuilder.bind(warningQueue).to(backupExchange);}
3. 告警消费者
package com.hong.springboot.rabbitmq.consumer;import com.hong.springboot.rabbitmq.config.ConfirmConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;
import java.util.Date;/*** @Description: 告警消费者* @Author: hong* @Date: 2024-03-10 17:54* @Version: 1.0**/
@Slf4j
@Component
public class WarningConsumer {//接收告警消息@RabbitListener(queues = ConfirmConfig.WARNING_QUEUE_NAME)public void receiveWarningMessage(Message message){String msg = new String(message.getBody());log.info("当前时间:{},备用交换机收到不可路由信息{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) , msg);}
}
先删了confirm.exchange交换机(改了配置)再启动项目,发送http://localhost:8080/confirm/sendMsg/Hi,JAVA小生不才