SpringCloud之Zuul自定义Fallback

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_31122833/article/details/97787392

场景:当路由调用服务时,服务宕机了,返回的页面或响应不友好,这是我们可以自定义自己的响应

实现:在Zuul里新写ZuulFallback类implements实现ZuulFallbackProvider,源码如下:

@Component
public class ZuulFallback implements ZuulFallbackProvider {
	@Override
	public ClientHttpResponse fallbackResponse() {
		return new ClientHttpResponse() {
			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.set("Content-Type", "text/html;charset=UTF-8");
				return headers;
			}
			@Override
			public InputStream getBody() throws IOException {
				// 当出现服务调用错误之后返回的内容
				// 服务端死掉,会自动找zuul的失败回退服务降级
				Result result = new Result();
				result.setType(TypeEnum.telentErr.getCode());
				RequestContext context = RequestContext.getCurrentContext();
				String serviceId =(String) context.get(SERVICE_ID_KEY);
				result.setMessage(serviceId+"服务不可用,请稍后再试!");
				return new ByteArrayInputStream(result.getMessage().getBytes("UTF-8"));
			}
			@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 最后做些什么
			}
		};
	}
	@Override
	public String getRoute() {
		// 设置好处理失败的路由
		return "*";
	}
}

测试:stop掉spring-cloud-website服务,然后调用这个服务的接口,直接返回:

spring-cloud-website服务不可用,请稍后再试!

猜你喜欢

转载自blog.csdn.net/qq_31122833/article/details/97787392