关于Zuul前2篇
1. 分布式04-Spring Cloud Zuul Api网关 一
2. 分布式04-Spring Cloud Zuul 二 Zuul拦截器
回退机制只有针对于服务出现故障,Zuul做的一些后续操作。
代码
package com.cloud.config; 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; import java.nio.charset.Charset; @Component public class TestFallbackProvider implements FallbackProvider { @Override public String getRoute() { //处理所有的服务 // return "*"; // 表明是为哪个微服务提供回退,*表示为所有微服务提供回退 return "eureka-server"; } @Override public ClientHttpResponse fallbackResponse(String route, Throwable cause) { //回退时的HTTP Status Code return this.response(HttpStatus.NOT_FOUND); } private ClientHttpResponse response(final HttpStatus status) { return new ClientHttpResponse() { @Override public HttpStatus getStatusCode() throws IOException { return status; } @Override public int getRawStatusCode() throws IOException { return status.value(); } @Override public String getStatusText() throws IOException { return status.getReasonPhrase(); } @Override public void close() { } @Override public InputStream getBody() throws IOException { //回退操作 return new ByteArrayInputStream("eureka-server服务不可用,请稍后再试。".getBytes()); } @Override public HttpHeaders getHeaders() { // headers设定 HttpHeaders headers = new HttpHeaders(); MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8")); headers.setContentType(mt); return headers; } }; } }
application.properties
zuul.routes.eureka-server.path=/public/* zuul.routes.eureka-server.service-id=eureka-server server.port= 12003 eureka.instance.hostname=localhost eureka.client.service-url.defaultZone= http://${eureka.instance.hostname}:12000/eureka/ eureka.client.healthcheck.enabled=true spring.application.name=eureka-Zuul
启动Zuul 和测试用的2个应用,打开Eureka,我们看到2个提供服务的应用eureka-server
eureka-server 提供一个 返回端口的接口
/** * http://localhost:12001/public/getPort * @param pageable * @return * @throws Exception */ @RequestMapping(value = "/getPort", method = RequestMethod.GET ) public Msg getport(Pageable pageable, String operatorId) throws Exception{ return Msg.MsgSuccess(port); }
调用 http://localhost:12003/public/getPort ,这个是通过我们的Zuul网关去调用 eureka-server的接口
这是正常访问的,时候我们可以看到getPort返回了2个应用的端口,而且 http 的status 是200.
现在我们终止掉端口为12001的应用。这时候Eureka还没有反应过来12001的应用已经无法提供服务,所有Zuul还是会调用12001的应用,这时候就会触发我们设置的回退机制。
可以看到12000的服务依然可以使用,而12001触发了我们的回退机制。
来源:oschina
链接:https://my.oschina.net/u/4039389/blog/3223406