当前位置: 首页 > news >正文

饿了吗网站做的比较好的地方全球搜索引擎

饿了吗网站做的比较好的地方,全球搜索引擎,免费的企业建站系统,wordpress主题使用教程1. 问题引入 消息从发送,到消费者接收,会经理多个过程: 其中的每一步都可能导致消息丢失,常见的丢失原因包括: 发送时丢失: 生产者发送的消息未送达exchange消息到达exchange后未到达queue MQ宕机&…

1. 问题引入

消息从发送,到消费者接收,会经理多个过程:
在这里插入图片描述

其中的每一步都可能导致消息丢失,常见的丢失原因包括:

  • 发送时丢失:
    • 生产者发送的消息未送达exchange
    • 消息到达exchange后未到达queue
  • MQ宕机,queue将消息丢失
  • consumer接收到消息后未消费就宕机

针对这些问题,RabbitMQ分别给出了解决方案:

  • 生产者确认机制
  • mq持久化
  • 消费者确认机制
  • 失败重试机制

2. 生产者消息确认

RabbitMQ提供了publisher confirm机制来避免消息发送到MQ过程中丢失。这种机制必须给每个消息指定一个唯一ID。消息发送到MQ以后,会返回一个结果给发送者,表示消息是否处理成功。

返回结果有两种方式:

  • publisher-confirm,发送者确认
    • 消息成功投递到交换机,返回ack
    • 消息未投递到交换机,返回nack
  • publisher-return,发送者回执
    • 消息投递到交换机了,但是没有路由到队列。返回ACK,及路由失败原因。
      在这里插入图片描述

注意:
在这里插入图片描述

2.1 修改配置

首先,修改publisher服务中的application.yml文件,添加下面的内容:

spring:rabbitmq:publisher-confirm-type: correlatedpublisher-returns: truetemplate:mandatory: true

说明:

  • publish-confirm-type:开启publisher-confirm,这里支持两种类型:
    • simple:同步等待confirm结果,直到超时
    • correlated:异步回调,定义ConfirmCallback,MQ返回结果时会回调这个ConfirmCallback
  • publish-returns:开启publish-return功能,同样是基于callback机制,不过是定义ReturnCallback
  • template.mandatory:定义消息路由失败时的策略。true,则调用ReturnCallback;false:则直接丢弃消息

2.2 定义Return回调

每个RabbitTemplate只能配置一个ReturnCallback,因此需要在项目加载时配置:

修改publisher服务,添加一个:

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {// 获取RabbitTemplateRabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);// 设置ReturnCallbackrabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {// 投递失败,记录日志log.info("消息发送失败,应答码{},原因{},交换机{},路由键{},消息{}",replyCode, replyText, exchange, routingKey, message.toString());// 如果有业务需要,可以重发消息});}
}

2.3 定义ConfirmCallback

ConfirmCallback可以在发送消息时指定,因为每个业务处理confirm成功或失败的逻辑不一定相同。

在publisher服务的测试类中,定义一个单元测试方法:

public void testSendMessage2SimpleQueue() throws InterruptedException {// 1.消息体String message = "hello, spring amqp!";// 2.全局唯一的消息ID,需要封装到CorrelationData中CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());// 3.添加callbackcorrelationData.getFuture().addCallback(result -> {if(result.isAck()){// 3.1.ack,消息成功log.debug("消息发送成功, ID:{}", correlationData.getId());}else{// 3.2.nack,消息失败log.error("消息发送失败, ID:{}, 原因{}",correlationData.getId(), result.getReason());}},ex -> log.error("消息发送异常, ID:{}, 原因{}",correlationData.getId(),ex.getMessage()));// 4.发送消息rabbitTemplate.convertAndSend("task.direct", "task", message, correlationData);// 休眠一会儿,等待ack回执Thread.sleep(2000);
}

3. 消息持久化

生产者确认可以确保消息投递到RabbitMQ的队列中,但是消息发送到RabbitMQ以后,如果突然宕机,也可能导致消息丢失。

要想确保消息在RabbitMQ中安全保存,必须开启消息持久化机制。

  • 交换机持久化
  • 队列持久化
  • 消息持久化

3.1 交换机持久化

RabbitMQ中交换机默认是非持久化的,mq重启后就丢失。

SpringAMQP中可以通过代码指定交换机持久化:

@Bean
public DirectExchange simpleExchange(){// 三个参数:交换机名称、是否持久化、当没有queue与其绑定时是否自动删除return new DirectExchange("simple.direct", true, false);
}

事实上,默认情况下,由SpringAMQP声明的交换机都是持久化的。

可以在RabbitMQ控制台看到持久化的交换机都会带上D的标示:
在这里插入图片描述

3.2 队列持久化

RabbitMQ中队列默认是非持久化的,mq重启后就丢失。

SpringAMQP中可以通过代码指定交换机持久化:

@Bean
public Queue simpleQueue(){// 使用QueueBuilder构建队列,durable就是持久化的return QueueBuilder.durable("simple.queue").build();
}

事实上,默认情况下,由SpringAMQP声明的队列都是持久化的。

可以在RabbitMQ控制台看到持久化的队列都会带上D的标示:
在这里插入图片描述

3.3 消息持久化

利用SpringAMQP发送消息时,可以设置消息的属性(MessageProperties),指定delivery-mode:

  • 1:非持久化
  • 2:持久化

用Java代码指定:
在这里插入图片描述

默认情况下,SpringAMQP发出的任何消息都是持久化的,不用特意指定。

4. 消费者消息确认

RabbitMQ是阅后即焚机制,RabbitMQ确认消息被消费者消费后会立刻删除。

而RabbitMQ是通过消费者回执来确认消费者是否成功处理消息的:消费者获取消息后,应该向RabbitMQ发送ACK回执,表明自己已经处理消息。

设想这样的场景:

  • 1)RabbitMQ投递消息给消费者
  • 2)消费者获取消息后,返回ACK给RabbitMQ
  • 3)RabbitMQ删除消息
  • 4)消费者宕机,消息尚未处理

这样,消息就丢失了。因此消费者返回ACK的时机非常重要。

而SpringAMQP则允许配置三种确认模式:

•manual:手动ack,需要在业务代码结束后,调用api发送ack。

•auto:自动ack,由spring监测listener代码是否出现异常,没有异常则返回ack;抛出异常则返回nack

•none:关闭ack,MQ假定消费者获取消息后会成功处理,因此消息投递后立即被删除

由此可知:

  • none模式下,消息投递是不可靠的,可能丢失
  • auto模式类似事务机制,出现异常时返回nack,消息回滚到mq;没有异常,返回ack
  • manual:自己根据业务情况,判断什么时候该ack

一般,我们都是使用默认的auto即可。

4.1 none模式

修改consumer服务的application.yml文件,添加下面内容:

spring:rabbitmq:listener:simple:acknowledge-mode: none # 关闭ack

修改consumer服务的SpringRabbitListener类中的方法,模拟一个消息处理异常:

@RabbitListener(queues = "simple.queue")
public void listenSimpleQueue(String msg) {log.info("消费者接收到simple.queue的消息:【{}】", msg);// 模拟异常System.out.println(1 / 0);log.debug("消息处理完成!");
}

测试可以发现,当消息处理抛异常时,消息依然被RabbitMQ删除了。

4.2 auto模式

再次把确认机制修改为auto:

spring:rabbitmq:listener:simple:acknowledge-mode: auto # 关闭ack

在异常位置打断点,再次发送消息,程序卡在断点时,可以发现此时消息状态为unack(未确定状态):
在这里插入图片描述

抛出异常后,因为Spring会自动返回nack,所以消息恢复至Ready状态,并且没有被RabbitMQ删除:
在这里插入图片描述

5. 消费失败重试机制

当消费者出现异常后,消息会不断requeue(重入队)到队列,再重新发送给消费者,然后再次异常,再次requeue,无限循环,导致mq的消息处理飙升,带来不必要的压力:
在这里插入图片描述

怎么办呢?

5.1 本地重试

我们可以利用Spring的retry机制,在消费者出现异常时利用本地重试,而不是无限制的requeue到mq队列。

修改consumer服务的application.yml文件,添加内容:

spring:rabbitmq:listener:simple:retry:enabled: true # 开启消费者失败重试initial-interval: 1000 # 初识的失败等待时长为1秒multiplier: 1 # 失败的等待时长倍数,下次等待时长 = multiplier * last-intervalmax-attempts: 3 # 最大重试次数stateless: true # true无状态;false有状态。如果业务中包含事务,这里改为false

重启consumer服务,重复之前的测试。可以发现:

  • 在重试3次后,SpringAMQP会抛出异常AmqpRejectAndDontRequeueException,说明本地重试触发了
  • 查看RabbitMQ控制台,发现消息被删除了,说明最后SpringAMQP返回的是ack,mq删除消息了

结论:

  • 开启本地重试时,消息处理过程中抛出异常,不会requeue到队列,而是在消费者本地重试
  • 重试达到最大次数后,Spring会返回ack,消息会被丢弃

5.2 失败策略

在之前的测试中,达到最大重试次数后,消息会被丢弃,这是由Spring内部机制决定的。

在开启重试模式后,重试次数耗尽,如果消息依然失败,则需要有MessageRecovery接口来处理,它包含三种不同的实现:

  • RejectAndDontRequeueRecoverer:重试耗尽后,直接reject,丢弃消息。默认就是这种方式

  • ImmediateRequeueMessageRecoverer:重试耗尽后,返回nack,消息重新入队

  • RepublishMessageRecoverer:重试耗尽后,将失败消息投递到指定的交换机

比较优雅的一种处理方案是RepublishMessageRecoverer,失败后将消息投递到一个指定的,专门存放异常消息的队列,后续由人工集中处理。

1)在consumer服务中定义处理失败消息的交换机和队列

@Bean
public DirectExchange errorMessageExchange(){return new DirectExchange("error.direct");
}
@Bean
public Queue errorQueue(){return new Queue("error.queue", true);
}
@Bean
public Binding errorBinding(Queue errorQueue, DirectExchange errorMessageExchange){return BindingBuilder.bind(errorQueue).to(errorMessageExchange).with("error");
}

2)定义一个RepublishMessageRecoverer,关联队列和交换机

@Bean
public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){return new RepublishMessageRecoverer(rabbitTemplate, "error.direct", "error");
}

完整代码:

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;@Configuration
public class ErrorMessageConfig {@Beanpublic DirectExchange errorMessageExchange(){return new DirectExchange("error.direct");}@Beanpublic Queue errorQueue(){return new Queue("error.queue", true);}@Beanpublic Binding errorBinding(Queue errorQueue, DirectExchange errorMessageExchange){return BindingBuilder.bind(errorQueue).to(errorMessageExchange).with("error");}@Beanpublic MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){return new RepublishMessageRecoverer(rabbitTemplate, "error.direct", "error");}
}

6. 总结

如何确保RabbitMQ消息的可靠性?

  • 开启生产者确认机制,确保生产者的消息能到达队列
  • 开启持久化功能,确保消息未消费前在队列中不会丢失
  • 开启消费者确认机制为auto,由spring确认消息处理成功后完成ack
  • 开启消费者失败重试机制,并设置MessageRecoverer,多次重试失败后将消息投递到异常交换机,交由人工处理

文章转载自:
http://dinncocapella.zfyr.cn
http://dinncomaizuru.zfyr.cn
http://dinncosemitotalitarian.zfyr.cn
http://dinnconazarene.zfyr.cn
http://dinncogittern.zfyr.cn
http://dinncoteleconnection.zfyr.cn
http://dinncoshqip.zfyr.cn
http://dinncoprotractor.zfyr.cn
http://dinncoupriver.zfyr.cn
http://dinncodressing.zfyr.cn
http://dinncosymbion.zfyr.cn
http://dinncotroposcatter.zfyr.cn
http://dinnconehemiah.zfyr.cn
http://dinncotropo.zfyr.cn
http://dinncoinasmuch.zfyr.cn
http://dinncorsd.zfyr.cn
http://dinncopsychognosy.zfyr.cn
http://dinnconondecreasing.zfyr.cn
http://dinncomisdemeanor.zfyr.cn
http://dinncobamboozlement.zfyr.cn
http://dinncoprovider.zfyr.cn
http://dinncospokewise.zfyr.cn
http://dinncomeionite.zfyr.cn
http://dinnconervous.zfyr.cn
http://dinncoirritancy.zfyr.cn
http://dinncotrimotored.zfyr.cn
http://dinncoenhydrous.zfyr.cn
http://dinncokitchen.zfyr.cn
http://dinncopalpi.zfyr.cn
http://dinncoundefinable.zfyr.cn
http://dinncobuckeen.zfyr.cn
http://dinncoablaut.zfyr.cn
http://dinncocondescension.zfyr.cn
http://dinncooutskirts.zfyr.cn
http://dinncoground.zfyr.cn
http://dinncoplebeianize.zfyr.cn
http://dinncopurpura.zfyr.cn
http://dinncoperilous.zfyr.cn
http://dinncosciomachy.zfyr.cn
http://dinncogromwell.zfyr.cn
http://dinncopreseason.zfyr.cn
http://dinncosudamina.zfyr.cn
http://dinncodistorted.zfyr.cn
http://dinncoendomysium.zfyr.cn
http://dinncoupperworks.zfyr.cn
http://dinncophosphocreatin.zfyr.cn
http://dinncocutlas.zfyr.cn
http://dinncodissimilar.zfyr.cn
http://dinncoinocula.zfyr.cn
http://dinncomicrotransmitter.zfyr.cn
http://dinncomondial.zfyr.cn
http://dinncolyricist.zfyr.cn
http://dinncogabonese.zfyr.cn
http://dinncounforested.zfyr.cn
http://dinncosolicit.zfyr.cn
http://dinncorecognize.zfyr.cn
http://dinncodecrescendo.zfyr.cn
http://dinncosinuosity.zfyr.cn
http://dinncohollowly.zfyr.cn
http://dinncounstep.zfyr.cn
http://dinncoafterwit.zfyr.cn
http://dinncohumourously.zfyr.cn
http://dinncorepandly.zfyr.cn
http://dinnconeuroplasm.zfyr.cn
http://dinncoparadise.zfyr.cn
http://dinncovicugna.zfyr.cn
http://dinncoopsin.zfyr.cn
http://dinncosoredial.zfyr.cn
http://dinncokalsomine.zfyr.cn
http://dinncoasphyxial.zfyr.cn
http://dinncoconch.zfyr.cn
http://dinncohexabasic.zfyr.cn
http://dinncogangmaster.zfyr.cn
http://dinncorecycle.zfyr.cn
http://dinncorompy.zfyr.cn
http://dinncoallotransplant.zfyr.cn
http://dinncopraecipe.zfyr.cn
http://dinncodeclinatory.zfyr.cn
http://dinncoshorefront.zfyr.cn
http://dinncofascicled.zfyr.cn
http://dinncoliken.zfyr.cn
http://dinncorhomboidal.zfyr.cn
http://dinncobrickwork.zfyr.cn
http://dinncostaple.zfyr.cn
http://dinncopugree.zfyr.cn
http://dinncooverfreight.zfyr.cn
http://dinncomaidenhead.zfyr.cn
http://dinncoterni.zfyr.cn
http://dinncoyerevan.zfyr.cn
http://dinncounhang.zfyr.cn
http://dinncowon.zfyr.cn
http://dinncogriseous.zfyr.cn
http://dinncoconvalescence.zfyr.cn
http://dinncointerisland.zfyr.cn
http://dinncotropicana.zfyr.cn
http://dinncopianoforte.zfyr.cn
http://dinncojube.zfyr.cn
http://dinncopaleogenetics.zfyr.cn
http://dinncocatechist.zfyr.cn
http://dinncorotc.zfyr.cn
http://www.dinnco.com/news/143642.html

相关文章:

  • 网站广告代理如何做嘉兴新站seo外包
  • 新手练习做网站哪个网站比较合适黄页引流推广网站软件免费
  • 用asp做网站遇到的问题拼多多关键词排名查询软件
  • 怎么查网站的浏览量网站优化和网站推广
  • 自己能建网站吗推广和竞价代运营
  • 遵义建设厅官方网站 元丰竞价排名推广
  • 品牌 网站建设泰州网站建设优化
  • 大型网站 建设意义西安网约车平台
  • 梅州生态建设有限公司网站站内营销推广方式
  • 做网站必须要备案吗网络宣传方式有哪些
  • 长沙网页设计哪个公司好兰州网络推广优化服务
  • 小学学校网站建设方案网络营销发展方案策划书
  • 网站建设与制作模板百度地图人工电话
  • 响应式衣柜网站东莞全网营销推广
  • 有哪些免费网站可以做店招百度网站怎么申请注册
  • 成都住建局官网站首页seo实战培训教程
  • 网站设计作业多少钱关键词歌词图片
  • 新网站建设运营年计划书今日时政新闻热点
  • 天津 公司网站建设网站排名查询站长之家
  • 上海网站建设q.479185700棒企业培训课程名称大全
  • 做班级玩网站做哪些方面网络推广渠道公司
  • 在线crm什么软件好安阳seo
  • 网站专题页面设计欣赏百度网站入口
  • 网站开发合同 中英文淘宝优化
  • 手机网站开发的目的必应搜索引擎入口
  • 什么是网站国内高速空间淘宝运营培训课程免费
  • 调整网站模板大小银行营销技巧和营销方法
  • app软件开发专业公司旺道seo软件
  • 重庆学校网站建设seo关键字排名
  • 某市政府信息网站建设方案武汉网站优化公司