springboot 引用不同地址的RabbitMQ

application配置

#fubao
spring.rabbitmq.fubao.host=192.168.x.xx
spring.rabbitmq.fubao.port=5672
spring.rabbitmq.fubao.username=xxx
spring.rabbitmq.fubao.password=xxx
spring.rabbitmq.fubao.virtual-host=xx
#zcnews
spring.rabbitmq.zcnews.host=192.168.x.xxx
spring.rabbitmq.zcnews.port=5672
spring.rabbitmq.zcnews.username=xxx
spring.rabbitmq.zcnews.password=xxxx
spring.rabbitmq.zcnews.virtual-host=xx

配置Rabbitmq config

@Configuration
@EnableRabbit
public class RabbitConfig {


    @Value("${spring.rabbitmq.fubao.host}")
    private String host1Addresses;

    @Value("${spring.rabbitmq.fubao.username}")
    private String host1Username;

    @Value("${spring.rabbitmq.fubao.password}")
    private String host1Password;

    @Value("${spring.rabbitmq.fubao.virtual-host}")
    private String host1VirtualHost;

    @Value("${spring.rabbitmq.zcnews.host}")
    private String host2Addresses;

    @Value("${spring.rabbitmq.zcnews.username}")
    private String host2Username;

    @Value("${spring.rabbitmq.zcnews.password}")
    private String host2Password;

    @Value("${spring.rabbitmq.zcnews.virtual-host}")
    private String host2VirtualHost;

    @Bean
    @Primary
    public CachingConnectionFactory  fubaoConnectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory(host1Addresses, 5672);
        factory.setUsername(host1Username);
        factory.setPassword(host1Password);
        factory.setVirtualHost(host1VirtualHost);
        return factory;
    }

    @Bean(name = "fubaoRabbitListenerContainerFactory")
    public RabbitListenerContainerFactory<?> fubaoRabbitListenerContainerFactory( @Qualifier("fubaoConnectionFactory")CachingConnectionFactory fubaoConnectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(fubaoConnectionFactory);
        return factory;
    }


    @Bean(name = "fubaoRabbitTemplate")
    public RabbitTemplate fubaoRabbitTemplate() {
        return new RabbitTemplate(fubaoConnectionFactory());
    }


    @Bean
    public CachingConnectionFactory zcnewsConnectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory(host2Addresses, 5672);
        factory.setUsername(host2Username);
        factory.setPassword(host2Password);
        factory.setVirtualHost(host2VirtualHost);
        return factory;
    }

    @Bean(name = "zcnewsRabbitTemplate")
    public RabbitTemplate zcnewsRabbitTemplate() {
        return new RabbitTemplate(zcnewsConnectionFactory());
    }

    @Bean(name = "zcnewsRabbitListenerContainerFactory")
    public RabbitListenerContainerFactory<?> zcnewsRabbitListenerContainerFactory(@Qualifier("zcnewsConnectionFactory") CachingConnectionFactory zcnewsConnectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(zcnewsConnectionFactory);
        return factory;
    }
}

发送消息

@Slf4j
@Component
public class RabbitMQUtil {

    @Autowired
    private RabbitTemplate fubaoRabbitTemplate;

    /**
     * 发送普通消息
     * @param exchange 交换机
     * @param routingKey 路由键
     * @param message 消息内容
     */
    public void sendMessage(String exchange, String routingKey, Object message) {
        try {
            fubaoRabbitTemplate.convertAndSend(exchange, routingKey, message);
            log.info("消息发送成功: exchange={}, routingKey={}, message={}", exchange, routingKey, message);
        } catch (Exception e) {
            log.error("消息发送失败: exchange={}, routingKey={}, message={}", exchange, routingKey, message, e);
            throw new RuntimeException("消息发送失败", e);
        }
    }


    /**
     * 发送带有消息确认的消息
     * @param exchange 交换机
     * @param routingKey 路由键
     * @param message 消息内容
     */
    public void sendMessageWithConfirm(String exchange, String routingKey, Object message) {
        fubaoRabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("消息发送确认成功: exchange={}, routingKey={}, message={}",
                        exchange, routingKey, message);
            } else {
                log.error("消息发送确认失败: exchange={}, routingKey={}, message={}, cause={}",
                        exchange, routingKey, message, cause);
            }
        });

        fubaoRabbitTemplate.setReturnCallback((msg, replyCode, replyText, tmpExchange, tmpRoutingKey) -> {
            log.error("消息发送失败: exchange={}, routingKey={}, replyCode={}, replyText={}",
                    tmpExchange, tmpRoutingKey, replyCode, replyText);
        });

        sendMessage(exchange, routingKey, message);
    }
}

消费消息

@Slf4j
@Component
public class PullNewsRabbitMQListener implements ChannelAwareMessageListener {

    @Resource
    private NewsService newsService;


    //重试次数
    private int retryCount = 0;

    //queues消费的队列  ackMode确认模式 MANUAL 手动确认
    @RabbitListener(queues = "q_fubao_news", containerFactory = "fubaoRabbitListenerContainerFactory",ackMode = "MANUAL")
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        // 消息的唯一标识id
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("接收到mq信息,处理的articleId为:" + new String(message.getBody()));
        try{
            //todo 开始业务处理
            String msg = new String(message.getBody());
            Integer articleId = Integer.parseInt(msg);
            newsService.pullNews(articleId);
            // 手动签收的第一个参数为消息的唯一标识id、第二个参数表示是否批量签收
            channel.basicAck(deliveryTag,false);
            log.info("消费mq消息成功,articleId为:{}",articleId);
        }catch (Exception e){
            retryCount++;
            log.error(String.format("articleId:%s,%d次重试失败,异常信息为:%s",new String(message.getBody()),retryCount,e.getMessage()));
            //重新抛出异常  触发重试机制
            throw e;
        }
        finally {
            //重试次数达到限制
            if (retryCount == 3) {
                log.error(String.format("新闻后台数据入库失败,articleId为:%s",new String(message.getBody())));
                //不重新入队,发送到死信队列
                // 手动拒绝签收的第一个参数为消息id、
                // 第二个参数表示是否批量签收
                // 第三个参数消息是否重回队列
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            }
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值