目標
- 開啟zuul重試機制
- 配置Ribbon
- 配置hystrix
zuul本身已經(jīng)引入了對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中的內(nèi)容編碼一致,否則容易亂碼
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return headers;
}
/**
* 網(wǎng)關向api服務請求是失敗了缓升,但是消費者客戶端向網(wǎng)關發(fā)起的請求是OK的鼓鲁,
* 不應該把api的404,500等問題拋給客戶端
* 網(wǎng)關和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
這里有點問題,重試策略沒有生效港谊,直接服務降級了骇吭。。歧寺。