SpringCloud之Zuul网关

1、zuul网关服务

SpringCloud之Zuul网关_第1张图片

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.yzm</groupId>
        <artifactId>springcloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>zuul</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

启动类
@EnableZuulProxy:启用zuul网关代理

@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ZuulApplication {
	。。。
}

application.yml

server:
  port: 8096

spring:
  application:
    name: service-zuul

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8088/eureka/

zuul:
  routes:
    ribbon-ha: /api-a/**
    ribbon-hi:
      path: /api-b/**
    feign_haha:
      serviceId: feign-ha
      path: /api-c/**

路由规则:
请求url带有 /api-a/ 的路由到 ribbon-ha 服务(spring.application.name)
请求url带有 /api-b/ 的路由到 ribbon-hi 服务
请求url带有 /api-c/ 的路由到 feign-ha 服务(feign_haha 别名)

2、路由转发

依次启动 eureka、zuul、ribbon-ha、ribbon-hi、feign-ha、feign-hi
SpringCloud之Zuul网关_第2张图片
http://localhost:8096/api-a/hello?name=yzm
SpringCloud之Zuul网关_第3张图片
http://localhost:8096/api-b/hello?name=yzm
SpringCloud之Zuul网关_第4张图片
http://localhost:8096/api-c/hello?name=yzm
SpringCloud之Zuul网关_第5张图片
配置文件中zuul没有配置feign-hi的路由,但zuul有个默认路由规则即:zuul_ip:zuul_post/service_id/url
http://localhost:8096/feign-hi/hello?name=yzm
SpringCloud之Zuul网关_第6张图片
所有请求都可以通过zuul正确路由到对应的服务上

二级路由
http://localhost:8096/api-a/ha?name=yzm
SpringCloud之Zuul网关_第7张图片
转发完成!

再启动ribbon-hi:18093
刷新
SpringCloud之Zuul网关_第8张图片
负载均衡!

3、zuul配置

url

zuul:
  routes:
    ribbon-ha: /api-a/**
    ribbon-hi:
      path: /api-b/**
#    feign_haha:
#      serviceId: feign-ha
#      path: /api-c/**
    feign_haha:
      path: /api-c/**
      # 转发到IP地址
      url: http://localhost:8094/
    baidu:
      path: /baidu/**
      # 转发到域名
      url: https://www.baidu.com/

http://localhost:8096/api-c/hello?name=yzm
SpringCloud之Zuul网关_第9张图片
http://localhost:8096/baidu/
SpringCloud之Zuul网关_第10张图片
虽然url也可以进行转发但是无法进行负载均衡,推荐使用serviceId进行配置

ignored

zuul:
  ignored-services: '*'
  ignored-patterns: /**/hello/**
  routes:
    ribbon-ha: /api-a/**
    ribbon-hi:
      path: /api-b/**
    feign_haha:
      serviceId: feign-ha
      path: /api-c/**

ignored-services:忽略服务,只接受routes列表中的服务,默认规则的IP:PORT/serviceid/这种就无法转发
ignored-patterns: 忽略请求中带有hello的转发
SpringCloud之Zuul网关_第11张图片
SpringCloud之Zuul网关_第12张图片
SpringCloud之Zuul网关_第13张图片

prefix

zuul:
  prefix: /yzm
  # 对所有服务有效
  # stripPrefix: false
  routes:
    ribbon-ha: /api-a/**
    ribbon-hi:
      path: /api-b/**
    feign_haha:
      serviceId: feign-ha
      path: /api-c/**
      # 只对feign-ha服务有效
      stripPrefix: false

prefix:带有前缀的请求才会被拦截
stripPrefix:默认true,增加的前缀在转发之前剔除,false不剔除
SpringCloud之Zuul网关_第14张图片
没有前缀不拦截
SpringCloud之Zuul网关_第15张图片
SpringCloud之Zuul网关_第16张图片
多了前缀,没有对应接口,访问失败

4、回调

zuul:
  ignored-services: '*'
  routes:
    ribbon-ha: /api-a/**
    ribbon-hi:
      path: /api-b/**
    feign_haha:
      serviceId: feign-ha
      path: /api-c/**

拦截api-a请求路由到ribbon-ha时,ribbon-ha服务挂了,此时显示
SpringCloud之Zuul网关_第17张图片
编写回调

package com.yzm.zuul.filter;

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.StandardCharsets;

@Component
public class MyFallbackProvider implements FallbackProvider {

    @Override
    public String getRoute() {
        // 服务id,如果需要所有调用都支持回退,则return "*"或return null
        return "ribbon-ha";
    }

    @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 msg = route + ": 服务异常";
                return new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }
        };
    }
}

重启zuul,再次访问
SpringCloud之Zuul网关_第18张图片

5、过滤器

  • filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下:
    • pre:路由之前
    • routing:路由之时
    • post: 路由之后
    • error:发送错误调用
  • filterOrder:过滤的顺序,数值越小优先级越高
  • shouldFilter:这里可以写逻辑判断,是否要过滤,本文true,永远过滤。
  • run:过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。
package com.yzm.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if (accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            } catch (Exception e) {
                //
            }
            return null;
        }
        log.info("ok");
        return null;
    }
}

上面的过滤器要求,请求中必须带有token参数
重启zuul,不带token访问
SpringCloud之Zuul网关_第19张图片
带token
SpringCloud之Zuul网关_第20张图片

相关链接

首页
上一篇:Feign服务
下一篇:Config配置

你可能感兴趣的:(spring,cloud,spring,cloud)