spring cloud 容錯之zuul回退和Zuul過濾器
阿新 • • 發佈:2018-12-25
回復 ase 回退 實現接口 etl 微服務 ade err gets
一、容錯:Zuul回退
如果微服務下線了,針對每個微服務,都需要回復一個中文提示,而不是報異常
1、新建ConsumerFallbackProvider.java
package com.pupeiyuan.fallback; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Component; @Component public class ConsumerFallbackProvider implementsZuulFallbackProvider { @Override public ClientHttpResponse fallbackResponse() { return new ClientHttpResponse() { @Override public HttpHeaders getHeaders() { // headers設定 HttpHeaders headers = new HttpHeaders(); MediaType mt= new MediaType("application","json", Charset.forName("UTF-8")); headers.setContentType(mt); return headers; } @Override public InputStream getBody() throws IOException { // 響應體 return new ByteArrayInputStream(("moveserver微服務不可用,請稍後再試。" + ConsumerFallbackProvider.this.getRoute()).getBytes()); } @Override public String getStatusText() throws IOException { return HttpStatus.BAD_REQUEST.getReasonPhrase(); } @Override public HttpStatus getStatusCode() throws IOException { return HttpStatus.BAD_REQUEST; } @Override public int getRawStatusCode() throws IOException { return HttpStatus.BAD_REQUEST.value(); } @Override public void close() { // TODO Auto-generated method stub } }; } @Override public String getRoute() { // TODO Auto-generated method stub return "MOVESERVER"; } }
2、效果
二、Zuul過濾器
zuul還提供了過濾功能, 只要實現接口ZuulFilter即可對請求先進行篩選和過濾之後再路由到具體服務。
1.新增PreZuulFilter.java
package com.pupeiyuan.fallback; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; @Component public class PreZuulFilter extends ZuulFilter { private static final Logger LOGGER = LoggerFactory.getLogger(PreZuulFilter.class); @Override public boolean shouldFilter() { return true; } @Override public Object run() { HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); String host = request.getRemoteHost(); PreZuulFilter.LOGGER.info("請求的host:{}", host); return null; } @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 1; } }
2.效果如下
spring cloud 容錯之zuul回退和Zuul過濾器