SpringCloud Micro Services (05): Zuul component to achieve routing gateway control

A, Zuul components Introduction

1, the basic concept

Zuul main gateway to provide dynamic routing, monitoring, resiliency, security management and control functions. In a distributed system, the micro-service system for a plurality of micro-split service modules, to route the user's request through a gateway zuul forwarded to the specific micro-services module.

2, the role of Zuul

1) according to different strategies, it forwards the request to a different service up;

2) aggregation API interface, unified external exposure, improve system security;

3) implement a unified request filtering, and fuse downgrade services;

3, case structure

The boot sequence is as follows:

# 注册中心
node05-eureka-7001
# 两个服务提供者
node05-provider-6001
node05-provider-6002
# 网关控制
node05-zuul-7002

After a successful start, the registry is shown below:

Two, Zuul use Comments

1, dependent on the core

<!-- 路由网关 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>

2, the core configuration file

server:
  port: 7002
spring:
  application:
    name: cloud-node05-parent
eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://registry01.com:7001/eureka/
zuul:
  # 前缀,可以用来做版本控制
  prefix: /v1
  # 禁用默认路由,执行配置的路由
  ignored-services: "*"
  routes:
    # 配置6001接口微服务
    pro6001:
      serviceId: node05-provider-6001
      path: /api-6001/**
    # 配置6002接口微服务
    pro6002:
      serviceId: node05-provider-6002
      path: /api-6002/**
  • Start Class Notes: @EnableZuulProxy

3, unified service downgrade

FallbackProvider implement an interface, a custom prompt response.

@Component
public class FallBackConfig implements FallbackProvider {
    private static final Logger LOGGER = LoggerFactory.getLogger(FallBackConfig.class) ;
    @Override
    public ClientHttpResponse fallbackResponse(Throwable cause) {
        // 捕获超时异常,返回自定义信息
        if (cause instanceof HystrixTimeoutException) {
            return response(HttpStatus.GATEWAY_TIMEOUT);
        } else {
            return fallbackResponse();
        }
    }
    private ClientHttpResponse response(final HttpStatus status) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() {
                return status;
            }
            @Override
            public int getRawStatusCode() {
                return status.value();
            }
            @Override
            public String getStatusText() {
                return status.getReasonPhrase();
            }
            @Override
            public void close() {
                LOGGER.info("close");
            }
            @Override
            public InputStream getBody() {
                String message =
                        "{\n" +
                            "\"code\": 200,\n" +
                            "\"message\": \"微服务飞出了地球\"\n" +
                        "}";
                return new ByteArrayInputStream(message.getBytes());
            }
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
    @Override
    public String getRoute() {
        return "*";
    }
    @Override
    public ClientHttpResponse fallbackResponse() {
        return response(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

4, unified filter

ZuulFilter class inheritance, custom filtering action.

@Component
public class FilterConfig extends ZuulFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(FilterConfig.class) ;
    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 0;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext() ;
        try {
            doBizProcess(requestContext);
        } catch (Exception e){
            LOGGER.info("异常:{}",e.getMessage());
        }
        return null;
    }

    public void doBizProcess (RequestContext requestContext) throws Exception {
        HttpServletRequest request = requestContext.getRequest() ;
        String reqUri = request.getRequestURI() ;
        if (!reqUri.contains("getAuthorInfo")){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            requestContext.getResponse().getWriter().print("Path Is Error...");
        }
    }
}

5, the testing process

1) Test the gateway configuration

Accessing an interface to respond to normal, indicating that the gateway configuration to take effect:

http://localhost:7002/v1/api-6001/getAuthorInfo/1
http://localhost:7002/v1/api-6002/getAuthorInfo/2

2) Testing Services downgraded

6001 shut down the service, access the interface again displays the following information, indicating degradation of service policy is in effect:

{
    "code": 200,
    "message": "微服务飞出了地球"
}

3) Test Filter

Because the request URI does not match GetAuthorInfo, therefore intercepted described filter little effect:

http://localhost:7002/v1/api-6001/
响应提示:
Path Is Error...

Third, the source address

GitHub地址:知了一笑
https://github.com/cicadasmile
码云地址:知了一笑
https://gitee.com/cicadasmile

Guess you like

Origin www.cnblogs.com/cicada-smile/p/11355224.html