本节探讨Zuul的高级特性。
TIPS:
笔者已经写过很多Zuul相关的文章,对于已经写过的内容,就不再啰嗦一遍了,直接贴地址吧。
过滤器是Zuul的核心,Zuul大多功能都是基于过滤器实现的。详见:Spring Cloud Zuul过滤器详解 ,文章着重探讨了Zuul过滤器的生命周期、如何自定义过滤器、如何禁用指定过滤器等。
Zuul内置了很多过滤器,这些过滤器帮助我们实现各种能力,来分析一下内置过滤器有哪些,分别是干嘛的。
详见:Spring Cloud内置的Zuul过滤器详解
跟我学Spring Cloud(Finchley版)-16-Zuul 讲过,Zuul整合了Hystrix,而Hystrix提供fallback的能力。
前文已详细讲过通用方式提供fallback、Feign提供fallback。如果不记得如何提供Fallback,可前往如下文章复习。
跟我学Spring Cloud(Finchley版)-13-通用方式使用Hystrix跟我学Spring Cloud(Finchley版)-14-Feign使用Hystrix 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 /** * @author itmuch.com */ @Component public class MyFallbackProvider implements FallbackProvider { @Override public String getRoute() { // 表明是为哪个微服务提供回退,*表示为所有微服务提供回退 return "*"; } @Override public ClientHttpResponse fallbackResponse(String route, Throwable cause) { if (cause instanceof HystrixTimeoutException) { return response(HttpStatus.GATEWAY_TIMEOUT); } else { return this.fallbackResponse(); } } public ClientHttpResponse fallbackResponse() { return this.response(HttpStatus.INTERNAL_SERVER_ERROR); } private ClientHttpResponse response(final HttpStatus status) { return new ClientHttpResponse() { @Override public HttpStatus getStatusCode() throws IOException { return status; } @Override public int getRawStatusCode() throws IOException { return status.value(); } @Override public String getStatusText() throws IOException { return status.getReasonPhrase(); } @Override public void close() { } @Override public InputStream getBody() throws IOException { return new ByteArrayInputStream("服务不可用,请稍后再试。".getBytes()); } @Override public HttpHeaders getHeaders() { // headers设定 HttpHeaders headers = new HttpHeaders(); MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8")); headers.setContentType(mt); return headers; } }; } }这样,当Zuul后端服务发生异常时,就会进到该Fallback类,并返回服务不可用,请稍后再试。 。