客户端访问微服务,通过网关,如果服务挂掉了,自然也是需要熔断的.否则体验很不好.
package com.datang.pet.zuul.serverfallback; import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; 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; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /*core服务降级*/ @Component public class CoreFallback implements FallbackProvider { @Override public String getRoute() { return "core"; } @Override public ClientHttpResponse fallbackResponse(String route, Throwable cause) { return new ClientHttpResponse() { @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 InputStream getBody() throws IOException { String response = "{ " + " "msg": "core服务失去联系,请联系管理员", " + " "code": 400, " + " "data": null " + "}"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(response.getBytes()); return byteArrayInputStream; } @Override public HttpHeaders getHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return httpHeaders; } }; } }
但是只是这么写,把服务关掉以后并没有降级熔断,客户端收到的是404.
找了好久才发现,原来是配置文件少配置了.
zuul.routes.core=/core/**
这个路由配置,原来以为只是一个服务名映射,但看来还是不简单的.以上配置 .core是服务名,/core/** 指的是这个路径下的都转发到core服务