SpringCloud(十) GateWay网关

1、Gateway新一代网关

Gateway整合nacospom依赖


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.smartgisgroupId>
    <artifactId>smartgis-gatewayartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>smartgis-gatewayname>
    <description>Demo project for Spring Bootdescription>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.5.RELEASEversion>

        <relativePath/> 
    parent>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
        <nacos.version>0.2.1.RELEASEnacos.version>
        <spring-cloud.version>Finchley.SR1spring-cloud.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.8.0version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.8.0version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-loggingartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-gatewayartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
            <version>${nacos.version}version>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-alibaba-nacos-configartifactId>
            <version>${nacos.version}version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.16.18version>
        dependency>
    dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
        <finalName>smartgis-gatewayfinalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <mainClass>com.smartgis.GatewayStarterApplicationmainClass>
                    <layout>ZIPlayout>
                configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

1.1 是什么

在这里插入图片描述
SpringCloud(十) GateWay网关_第1张图片
在这里插入图片描述
SpringCloud(十) GateWay网关_第2张图片

1.2 能干啥

  • 反向代理
  • 鉴权
  • 流量控制
  • 熔断
  • 日志监控

1.3 微服务架构中网关在哪里

SpringCloud(十) GateWay网关_第3张图片

2、Spring Cloud Gateway特性

SpringCloud(十) GateWay网关_第4张图片

3、WebFlux

SpringCloud(十) GateWay网关_第5张图片

4、三大核心概念

4.1 Route(路由)

路由是构建网关的基本模块,它由ID,目标URL,一系列的断言和过滤器组成,如果断言为true则匹配该路由

4.2 Predicate(断言)

开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由

4.3 Filter(过滤)

指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求路由前或之后对请求进行修改

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-T1fyvECi-1592009981442)(C:\Users\ZQY\AppData\Local\Temp/1588225321793.png)]

核心逻辑:

路由转发 + 执行过滤器链

5、入门配置

5.1 新建 Module(cloud-gateway-gateway9527)

5.2 POM


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2020artifactId>
        <groupId>com.qygroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>cloud-gateway-gateway9527artifactId>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-gatewayartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
        
        <dependency>
            <groupId>com.qygroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

project>

5.3 YML

server:
  port: 9527

spring:
  application:
    name: cloud-gateway

eureka:
  instance:
    hostname: cloud-gateway-service
  client: #服务体重这provider注册进eureka服务列表内
  service-url: 
       register-with-eureka: true
       fetch-registry: true
       defaultZone: http://eureka7001.com:7001/eureka

5.4 service 无

5.5 controller 无

5.6 主启动

@SpringBootApplication
@EnableEurekaClient
public class GatewayMain9527 {
    public static void main(String[] args) {
        SpringApplication.run(GatewayMain9527.class,args);
    }
}

5.7 9527网关如何做路由映射?

cloud-provider-payment8001看看controller的访问地址

我们目前不想暴露8001端口,希望在8001外面套一层9527

5.8 YML新增网关配置

更改9572的yml

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: payment_routh            # 路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001   # 匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/**     # 断言,路径相匹配的进行路由

        - id: payment_routh2
          uri: http://localhost:8001
          predicates:
            - Path=/payment/lb/**

eureka:
  instance:
    hostname: cloud-gateway-service
  client: #服务体重这provider注册进eureka服务列表内
  service-url:
       register-with-eureka: true
       fetch-registry: true
       defaultZone: http://eureka7001.com:7001/eureka

5.9 测试

SpringCloud(十) GateWay网关_第6张图片

若出现上图错误,是因为gateway的依赖和web依赖产生了冲突!

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-actuatorartifactId>
dependency>

访问测试 :

  • 添加网关前 : http://localhost:8001/payment/get/3
  • 添加网关后 : http://localhost:9527/payment/get/3

淡化了真实地址和端口号

5.10 YML配置说明

Gateway网关路由配置有两种方式:

  • 在配置文件yml中配置(见上面)
  • 代码中注入RouteLocator的Bean(用配置类)

代码中注入RouteLocator的Bean

@Configuration
public class MyConfig {
    @Bean
    public RouteLocator getRouteLocator(RouteLocatorBuilder builder){
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route(
                "path_route_01",   // 这个是id
                r -> r.path("/guonei").  // 访问 http://localhost:9527/guonei 地址后边的guonei
                        uri("http://news.baidu.com/guonei")).  //访问http://localhost:9527/guonei 跳转到该地址
                build();
        return routes.build();
    }
}

访问 http://localhost:9527/guone

6、配置动态路由

6.1 默认情况

默认情况下Gateway会根据注册中心注册的服务列表,以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能

6.2 启动:

一个eureka7001 + 两个服务提供者 8001/8002

6.3 POM

     
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>

6.4 YML

在9527的yml中添加下列配置:

      discovery:
         locator:
            enabled: true # 开启从注册中心动态创建路由的功能,利用微服务名进行路由

总的yml:还要把写死的uri换掉

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # 开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh            # 路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001   # 匹配后提供服务的路由地址
          uri: lb://cloud-payment-service # 匹配后提供服务的路由地址
          predicates:                  # uri + Path : http://localhost:8001/payment/get/**
            - Path=/payment/get/**     # 断言,路径相匹配的进行路由

        - id: payment_routh2
          #uri: http://localhost:8001
          uri: lb://cloud-payment-service # 匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**

eureka:
  instance:
    hostname: cloud-gateway-service
  client: #服务体重这provider注册进eureka服务列表内
    service-url:
       register-with-eureka: true
       fetch-registry: true
       defaultZone: http://eureka7001.com:7001/eureka

访问 : http://localhost:9527/payment/lb

7、Predicate的使用

7.1 是什么

SpringCloud(十) GateWay网关_第7张图片

7.2 After

yml:

那么里边的时间我们怎么来得到呢?

SpringCloud(十) GateWay网关_第8张图片

直接输出就可以得到了。

7.3 Cookie

yml:

不带cookie的访问:

访问失败!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kiTr3yut-1592009981445)(C:\Users\ZQY\AppData\Local\Temp/1588238003851.png)]

带有cookie的访问:

访问成功!

SpringCloud(十) GateWay网关_第9张图片

8、Filter

自定义过滤器

自定义全局GlobalFilter

两个主要接口:

implements GlobalFilter,Ordered

能干吗:

全局日志记录,统一网关鉴权 …

代码:

一:实现接口

二:@Component 加入spring

三:写代码

@Component
public class MyGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("******come in MyGatewayFilter : "+new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null){
            System.out.println("********用户名为null,非法用户,/(ㄒoㄒ)/~~");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE); //如果失败了设置一下不能接收的状态码
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;  // 数字越小,优先级越高
    }
}

测试:

访问 http://localhost:9527/payment/lb?uname=z2

server:
  port: 88
spring:
  application:
    name: gulimall-gateway2
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      discovery:      #是否与服务发现组件进行结合,通过 serviceId(必须设置成大写) 转发到具体的服务实例。默认为false,设为true便开启通过服务中心的自动根据 serviceId 创建路由的功能。
        locator:      #路由访问方式:http://Gateway_HOST:Gateway_PORT/大写的serviceId/**,其中微服务应用名默认大写访问。
          enabled: true
      routes:
        - id: host_route
          uri: http://www.baidu.com
          predicates:
            - Path=/a/**

        - id: admin_route
          uri: lb://renren-fast
          predicates:
            - Path=/api/**
          filters:
            - RewritePath=/api/(?.*),/renren-fast/$\{segment}

你可能感兴趣的:(网关,过滤器,spring,java,分布式)