package com.itmuch.cloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.zuul.EnableZuulProxy;@SpringBootApplication@EnableZuulProxypublic class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); }}
package com.itmuch.cloud.fallback;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;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;//通过zuul(8040端口)访问user微服务http://localhost:8040/microservice-provider-user/simple/1//如果此时user微服务停掉,就会返回"fallbackmicroservice-provider-user",(使用的是hysitrcs的断路器功能)//feign的Fallback是针对一个类,zuul的Fallback是针对一个微服务。@Componentpublic class MyFallbackProvider implements ZuulFallbackProvider { @Override public String getRoute() { return "microservice-provider-user"; } @Override public ClientHttpResponse fallbackResponse() { return new ClientHttpResponse() { @Override public HttpStatus getStatusCode() throws IOException { return HttpStatus.BAD_REQUEST; } @Override public int getRawStatusCode() throws IOException { return HttpStatus.BAD_REQUEST.value(); } @Override public String getStatusText() throws IOException { return HttpStatus.BAD_REQUEST.getReasonPhrase(); } @Override public void close() { } @Override public InputStream getBody() throws IOException { return new ByteArrayInputStream(("fallback" + MyFallbackProvider.this.getRoute()).getBytes()); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return headers; } }; }}
spring: application: name: microservice-gateway-zuulserver: port: 8040eureka: client: service-url: defaultZone: http://user:password123@localhost:8761/eureka instance: prefer-ip-address: truehystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000ribbon: ConnectTimeout: 3000 ReadTimeout: 60000
4.0.0 com.itmuch.cloud microservice-spring-cloud 0.0.1-SNAPSHOT microservice-gateway-zuul-fallback jar UTF-8 org.springframework.cloud spring-cloud-starter-zuul org.springframework.cloud spring-cloud-starter-eureka