Spring Cloud 实战四:重试机制配置

上一篇写到,如何配置超时。在请求某个服务节点时,请求失败(如:请求超时、连接超时、服务宕机等,但并不是服务器报错),这时可以通过配置重试机制,重新请求其他服务。

首先引入依赖:

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>

1、rest+ribbon:重试机制配置

spring:
  application:
    name: client
  cloud:
   loadbalancer:
      retry:
        enabled: true
ribbon:
 # 同一实例最大重试次数,不包括首次调用
  MaxAutoRetries: 1
 # 重试其他实例的最大重试次数,不包括首次所选的server
  MaxAutoRetriesNextServer: 2
 # 是否所有操作都进行重试
  OkToRetryOnAllOperations: true

2、由于服务service-user 端口9001 调用接口中进行了Thread.sleep(120000L);所以请求超时之后,重试机制对9002端口进行了请求。

等待响应中:



最后请求结果,通过9002完成响应:



2、feign:重试机制配置

扫描二维码关注公众号,回复: 1589799 查看本文章

相关配置介绍

配置 说明
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 断路器的超时时间需要大于ribbon的超时时间,不然不会触发重试。
hello-service.ribbon.ConnectTimeout 请求连接的超时时间
hello-service.ribbon.ReadTimeout 请求处理的超时时间
hello-service.ribbon.OkToRetryOnAllOperations 是否对所有操作请求都进行重试
hello-service.ribbon.MaxAutoRetriesNextServer 重试负载均衡其他的实例最大重试次数,不包括首次server
hello-service.ribbon.MaxAutoRetries 同一台实例最大重试次数,不包括首次调用

添加以下配置即可

全局配置

# feign重试机制
ribbon:
    MaxAutoRetries: 1
    MaxAutoRetriesNextServer: 2
    OkToRetryOnAllOperations: true

局部配置:

# feign重试机制
SERVICE-USER:
  ribbon:
    MaxAutoRetries: 1
    MaxAutoRetriesNextServer: 2
    OkToRetryOnAllOperations: true

最后:github地址:https://github.com/houxi1234/demo.git

猜你喜欢

转载自blog.csdn.net/qq_32486913/article/details/80622847