Ribbon、Feign、Hystrix和Zuul超时重试设置(二)

上次写了一篇《Ribbon、Feign、Hystrix和Zuul超时重试设置(一)》,主要讲Ribbon和Feign的超时重试如何设置,这次来记录Hystrix的超时如何设置。

也是有一个服务供远程调用,跟之前一样
eureka-client:

@RequestMapping("/test")
public String test() {
    int sleepTime = new Random().nextInt(4000);
    System.out.println("sleepTime: " + sleepTime);
    try {
        Thread.sleep(sleepTime); //模拟网络延迟
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "test";
}

service-hystrix服务用来调用eureka-client中的接口
pom.xml:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

TestController:

@RestController
public class TestController {
	
	private final TestFeign testFeign;

	@Autowired
	public TestController(TestFeign testFeign) {
		this.testFeign = testFeign;
	}

	@GetMapping("/test")
	public String test() {
	    return testFeign.test();
	}
}

TestFeignService:

@FeignClient(value = "eureka-client", fallback = TestFeignServiceImpl.class)
@Repository
public interface TestFeignService {

    @RequestMapping("/test")
    String test();
}

TestFeignServiceImpl:

@Component
public class TestFeignServiceImpl implements TestFeignService {

    @Override
    public String test() {
        return "error";
    }
}

application.yml

server:
  port: 8002

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:5000/eureka/
spring:
  application:
    name: service-hystrix
feign:
  hystrix:
    enabled: true # 开启
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000 # 断路器的超时时间需要大于ribbon的超时时间,不然重试没有意义
ribbon:
  ReadTimeout: 2000
  ConnectionTimeout: 2000
  OkToRetryOnAllOperations: true
  MaxAutoRetriesNextServer: 1
  MaxAutoRetries: 0

运行如下:
在这里插入图片描述
可以看到,当超时并且重试也超时时,会执行降级逻辑,而不会报错。这里,断路器的超时时间需要大于ribbon的超时时间,不然重试没有意义。比如将一下设置去掉(默认值是1秒)或设置较低

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000

运行如下:
在这里插入图片描述
可以看到,第一次超时了并重试一次,第二次没有超时,但是页面已经显示error,执行降级逻辑,是因为远程调用的超时时间已经超过了断路器的超时时间,意思是第一次还没执行完就已经执行降级逻辑返回,虽然后台还在重试。所以断路器的超时时间要大于ribbon的超时时间,不然重试没有意义。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章