springcloud之ribbon请求重试_spring

1-服务消费者order_service中application.yml中开启日志

server:
  port: 9002
spring:
  application:
    name: service-order
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: 123456
  jpa:
    database: MySQL
    show-sql: true
    open-in-view: true
#配置Eureka
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/,http://localhost:8000/eureka/
  instance:
    prefer-ip-address: true #使用ip地址注册
#修改ribbon的负载均衡策略   服务名 - ribbon - NFLoadBalancerRuleClassName : 策略
#service-product:
#  ribbon:
#    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

logging:
  level:
    root: debug

2-运行

springcloud之ribbon请求重试_spring_02

关掉一个服务提供者,如9011

springcloud之ribbon请求重试_mysql_03

重试机制

1-引入spring的重试组件(坐标)

给服务消费者order_service的pom.xml中添加依赖

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

2-对ribbon进行重试配置

服务消费者order_service的application.yml中添加ribbon的重试配置

service-product:     #服务名,如service-product,order-service...
  ribbon:
    MaxAutoRetries: 1 #最大重试次数,当Eureka中可以找到服务,但是服务连不上时将会重试
    MaxAutoRetriesNextServer: 1 #切换实例的重试次数
    OkToRetryOnAllOperations: true # 对所有的操作请求都进行重试,如果是get则可以,如果是post,put等操作没有实现幂等的情况下是很危险的
    ConnectTimeout: 250 #请求连接的超时时间
    ReadTimeout: 1000 #请求处理的超时时间

停掉9011提供者时

springcloud之ribbon请求重试_spring_04