十、微服务网关之Zuul容错与回退

Spring Cloud中,Zuul默认已经整合了Hystrix

Zuul回退

编写Zuul回退类:

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
@Component
public class MyFallbackProvider implements FallbackProvider {
// 表明是为哪个微服务提供回退,*代表所有
@Override
public String getRoute() {
return "*";
}

@Override
public ClientHttpResponse fallbackResponse() {
return this.response(HttpStatus.INTERNAL_SERVER_ERROR);
}

@Override
public ClientHttpResponse fallbackResponse(Throwable cause) {
if (cause instanceof HystrixTimeoutException) {
return response(HttpStatus.GATEWAY_TIMEOUT);
} else {
return this.fallbackResponse();
}
}

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() {
HttpHeaders httpHeaders = new HttpHeaders();
MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
httpHeaders.setContentType(mediaType);
return httpHeaders;
}
};
}
}

当访问的微服务无法正常响应时,会返回如下内容:

1
服务不可用,请稍后再试。

该文章摘自《Spring Cloud 与 Docker 微服务架构实战(第二版)》

以上

LeoQin wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
0%