目标
- 开启zuul重试机制
- 配置Ribbon
- 配置hystrix
zuul本身已经引入了对Ribbon、hystrix的依赖,因此无需再次引入
修改配置
# 端口号
server.port=6001
# 服务名
spring.application.name=api
zuul.routes.account.path=/account/**
zuul.routes.account.serviceId=account
zuul.routes.wallet.path=/wallet/**
zuul.routes.wallet.serviceId=wallet
# 开启重试机制
zuul.retryable=true
# eureka服务注册中心地址
eureka.client.serviceUrl.defaultZone=http://localhost:5000/eureka/
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000
ribbon.ConnectTimeout=3000
ribbon.ReadTimeout=3000
ribbon.OkToRetryOnAllOperations=true
ribbon.MaxAutoRetries=1
ribbon.MaxAutoRetriesNextServer=1
增加ZuulFallBack类
@Component
public class ZuulFallBack implements FallbackProvider {
@Override
public String getRoute() {
return "*";
}
public ClientHttpResponse build(String message) {
return new ClientHttpResponse() {
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream(message.getBytes("UTF-8"));
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
//和body中的内容编码一致,否则容易乱码
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return headers;
}
/**
* 网关向api服务请求是失败了,但是消费者客户端向网关发起的请求是OK的,
* 不应该把api的404,500等问题抛给客户端
* 网关和api服务集群对于客户端来说是黑盒子
*/
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return HttpStatus.OK.value();
}
@Override
public String getStatusText() throws IOException {
return HttpStatus.OK.getReasonPhrase();
}
@Override
public void close() {
}
};
}
@Override
public ClientHttpResponse fallbackResponse() {
return build("gateway fall back");
}
@Override
public ClientHttpResponse fallbackResponse(Throwable cause) {
return build(cause.getCause().getMessage());
}
}
测试
访问 http://localhost:6001/wallet/getWallet?accessToken=11
image.png这里有点问题,重试策略没有生效,直接服务降级了。。。
网友评论