之前我們在eureka(參見Greenwich.SR2版本的Spring Cloud Eureka實例)中,服務消費方a-beautiful-client調用服務提供方a-bootiful-client,如果這時提供方掛掉或者請求超時的話,如何實現服務降級呢?spring cloud給我們提供了Hystrix這個斷路器,通過注解能很方便的實現。我們還是拿a-beautiful-client舉例,老套路,三板斧亮出:
1、pom里新增Hystrix的jar包引入:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
2、主類添加@EnableCircuitBreaker注解開啟熔斷;
3、實現類ConusmerServiceImpl添加注解啟用熔斷並指定降級方法@HystrixCommand(fallbackMethod = "backupCall"):
@Override @HystrixCommand(fallbackMethod = "backupCall") public String call(String name) { ResponseEntity resultResponseEntity = restTemplate.postForEntity(appServiceUrl + "hello?name=" + name, null, String.class); if (resultResponseEntity != null && resultResponseEntity.getBody() != null) { return name + " says: " + resultResponseEntity.getBody().toString(); } return null; } public String backupCall(String name) { return "Hi, I'm Hystix."; }
打完收工。注意熔斷方法backupCall的參數、返回類型需要跟原來的call方法保持一致。我們把服務提供方a-bootiful-client的全部或部分服務停掉,再通過http://localhost:8763/sayHello?name=world請求,會發現返回的是服務降級方法backupCall里的東西了:
我們上面是通過服務降級方法來實現的熔斷,其實也可以通過服務降級類來做,詳見Greenwich.SR2版本的Spring Cloud Feign實例。