Java高级教程之SpringCloud-8:Hystrix断路器结合FeignClient的容错机制
FeignClient支持容错机制,也就是当微服务不可用时仍返回一个响应结果,使业务不中断,但响应的结果会是模拟的结果或是错误的结果。因为微服务之间的调用,可能导致上游不可用而影响下游很多的服务不可用,如果在上游服务不可用时仍然能响应,就可以使系统有容错机制。
现在给ProductClient加上了fallback属性,指定如果服务不可用,就使用ProductClientFallback返回模拟的微服务结果。
package com.lpplpp.app.client; import com.lpplpp.app.model.Product; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(name="product-service", fallback = ProductClientFallback.class) public interface ProductClient { @RequestMapping(method = RequestMethod.GET, value = "/product/{id}", consumes = "application/json") Product getProductById(@PathVariable("id") Long id); }
增加ProductClient的实现类PrudctClientFallback:
package com.lpplpp.app.client; import com.lpplpp.app.model.Product; import org.springframework.stereotype.Component; @Component public class ProductClientFallback implements ProductClient { @Override public Product getProductById(Long id) { return new Product(1L,"mock product"); } }
在application.yml配置文件里,还需要设置一下feign开启为true。feign: hystrix: enabled: falsefeign: hystrix: enabled: false
正常访问http://localhost:8180/order/1返回结果:
{"id":1,"name":"mobile order","product":{"id":1,"name":"mobile"}}
停掉product-service微服务,返回结果会是:
{"id":1,"name":"mobile order","product":{"id":1,"name":"mock product"}}
如果没有容错,那order-service返回的是出错页面:Whitelabel Error Page