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的超時時間,不然重試沒有意義。

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