SpringCloud高版本在Zuul中使用fallback功能

如何在Zuul中使用fallback功能

我们在项目中使用Spring cloud zuul的时候,当我们的zuul进行路由分发时,如果后端服务没有启动,或者调用超时,这时候我们希望Zuul提供一种处理机制功能,而不是将异常暴露出来。

使用fallback非常简单只需要实现FallbackProvider类即可,定义MyFallbackProvider类并实现FallbackProvider,具体内容如下:

@Component
public class MyFallbackProvider implements FallbackProvider {
	
  @Override
  public String getRoute() {
    // 表明是为哪个微服务提供回退,*表示为所有微服务提供回退
    return "*";
  }

  @Override
  public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
	  return this.response(HttpStatus.INTERNAL_SERVER_ERROR);
  }
  
  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("服务不可用,请稍后再试。".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.yml 内容:

server:
  port: 5000
spring:
  application:
    name: api-geteway
zuul: 
  routes:
    api-a: 
      path: /user/**
      service-id: microservice-provider-user
    api-b: 
      path: /file/**
      service-id: microservice-file-upload  
  host:
    connect-timeout-millis: 15000 #HTTP连接超时要比Hystrix的大
    socket-timeout-millis: 60000   #socket超时
eureka:
  client:
    serviceUrl: 
      defaultZone: http://user:password123@localhost:8761/eureka
ribbon:
  ReadTimeout: 10000
  ConnectTimeout: 10000

  
 

pom.xml内容:



	4.0.0
	
	
		com.itmuch.cloud
		microservice-spring-cloud
		0.0.1-SNAPSHOT
	
	
	microservice-zuul
    jar

	
		1.8
	

	
		 
            org.springframework.cloud
            spring-cloud-starter-netflix-zuul
        	
	


只启动eureka和zuul后,在浏览器中输入请求地址,由于user微服务没有启动,zuul启用fallback显示服务不可用,请稍后再试。

你可能感兴趣的:(微服务,zuul,springCloud)