• Gateway基础使用


    推荐参考:
    Spring Cloud Gateway 参考指南
    Spring Cloud Gateway 服务网关的部署与使用详细介绍
    springCloud核心组件之网关(Gateway)
    spring-cloud-gateway(spring官网)
    spring-web-flux (spring官网)

    环境搭建

    pom.xml

    注意:要排除web的启动依赖

    
    <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.zzhuagroupId>
        <artifactId>demo-gatewayartifactId>
        <version>1.0-SNAPSHOTversion>
    
        <properties>
            <spring-boot.version>2.3.2.RELEASEspring-boot.version>
            <spring-cloud.version>Hoxton.SR9spring-cloud.version>
            <spring-cloud-alibaba.version>2.2.6.RELEASEspring-cloud-alibaba.version>
        properties>
    
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-starter-gatewayartifactId>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.bootgroupId>
                        <artifactId>spring-boot-starter-webartifactId>
                    exclusion>
                exclusions>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-redis-reactiveartifactId>
            dependency>
        dependencies>
    
        
        <dependencyManagement>
            <dependencies>
                
                <dependency>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-dependenciesartifactId>
                    <version>${spring-boot.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
                
                <dependency>
                    <groupId>org.springframework.cloudgroupId>
                    <artifactId>spring-cloud-dependenciesartifactId>
                    <version>${spring-cloud.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
                
                <dependency>
                    <groupId>com.alibaba.cloudgroupId>
                    <artifactId>spring-cloud-alibaba-dependenciesartifactId>
                    <version>${spring-cloud-alibaba.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
            dependencies>
        dependencyManagement>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    application.yml配置

    spring:
      cloud:
        gateway:
          enabled: true
          globalcors:
            cors-configurations: ## 见org.springframework.web.cors.reactive.DefaultCorsProcessor
              '[/**]':
                allowedOrigins: '*'
                allowedHeaders: '*'
                allowedMethods:
                  - GET
                  - POST
                  - PUT
                  - OPTIONS
          routes:
          
            - id: xs1
              uri: http://localhost:9090/
              predicates:
                - Path=/a/** ## 见: GatewayAutoConfiguration#pathRoutePredicateFactory()
              filters:
                - PrefixPath=/ ## 见 GatewayAutoConfiguration#PrefixPathGatewayFilterFactory
    
            - id: xs2
              uri: http://localhost:9090
              predicates:
                - Path=/b/**
              filters: 
                - RewritePath=/b/?(?>.*), /$\{segment} ## 在yml语法中要用$\代替$, 在代码中会替换回来
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    GatewayApp启动类

    @SpringBootApplication
    public class GatewayApp {
    
        public static void main(String[] args) {
    
            SpringApplication.run(GatewayApp.class, args);
    
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    自定义路由断言工厂&网关过滤器工厂

    路由断言工厂

    继承自AbstractRoutePredicateFactory,构造方法中需要调用父类的有参构造方法

    @Component
    public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {
    
        public MyRoutePredicateFactory() {
            super(MyRoutePredicateFactory.Config.class);
        }
    
        @Override
        public List<String> shortcutFieldOrder() {
            return Arrays.asList("headerName");
        }
    
        @Override
        public Predicate<ServerWebExchange> apply(Config config) {
            return exchange -> {
                ServerHttpRequest request = exchange.getRequest();
                if (request.getHeaders().containsKey(config.getHeaderName())) {
                    return true;
                }
                return false;
            };
        }
    
        public static class Config {
    
            private String headerName;
    
            public String getHeaderName() {
                return headerName;
            }
    
            public void setHeaderName(String headerName) {
                this.headerName = headerName;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    网关过滤器工厂

    前置过滤器工厂

    @Component
    public class MyPreGatewayFilterFactory extends AbstractGatewayFilterFactory<MyPreGatewayFilterFactory.Config> {
    
        public MyPreGatewayFilterFactory() {
            super(Config.class);
        }
    
        @Override
        public List<String> shortcutFieldOrder() {
            return Arrays.asList("name");
        }
    
        @Override
        public GatewayFilter apply(Config config) {
            return (exchange, chain) -> {
    
                System.out.println("enter my-pre filter");
    
                URI newUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI())
                        .queryParam("name", config.name)
                        .encode()
                        .build()
                        .toUri();
    
                ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri).build();
    
                return chain.filter(exchange.mutate().request(request).build());
            };
        }
    
        public static class Config{
    
            private String name;
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    后置过滤器工厂

    @Component  // 可参考: RewriteResponseHeaderGatewayFilterFactory
    public class MyPostGatewayFilterFactory extends AbstractGatewayFilterFactory<AbstractGatewayFilterFactory.NameConfig> {
    
        public MyPostGatewayFilterFactory() {
            super(NameConfig.class);
        }
    
        @Override
        public GatewayFilter apply(NameConfig config) {
            return (exchange, chain) ->
                    chain.filter(exchange)
                            .then(
                                    Mono.fromRunnable(() -> {
                                        ServerHttpResponse response = exchange.getResponse();
                                        response.getHeaders().add("name", "zzhua");
                                    })
                            );
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    修改配置文件
    spring:
      cloud:
        gateway:
          enabled: true
          globalcors:
            cors-configurations:
              '[/**]':
                allowedOrigins: '*'
                allowedHeaders: '*'
                allowedMethods:
                  - GET
                  - POST
                  - PUT
                  - OPTIONS
          routes:
            - id: xs1
              uri: http://localhost:9090/
              predicates:
                - Path=/a/**
              filters:
                - PrefixPath=/
    
            - id: xs2
              uri: http://localhost:9090
              predicates:
                - Path=/b/**
              filters:
                - RewritePath=/b/?(?>.*), /$\{segment}
    
    		## 使用自定义前置/后置过滤器
            - id: xs3
              uri: http://localhost:9090/
              predicates:
                - My=Authorization
              filters:
                - MyPre=zzhua
                - MyPost=
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    全局过滤器

    @Component // 只需要定义在spring容器中, 即可生效
    public class MyGlobalGateway implements GlobalFilter {
    
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            System.out.println("start...");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                System.out.println("end...");
            }));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    Pytorch面试题整理(2023.09.10)
    一文介绍使用 JIT 认证后实时同步用户更加优雅
    软件测试相关知识
    easyx库的学习(鼠标信息)
    小白终于解决了在学习Go中不知道Makefile是什么的难题
    《云原生-Kubernetes篇》深入剖析Kubernetes中pod的原理
    正则表达式详解及应用
    限流与下载接口请求数控制
    PostgreSQL对已有表增加自增序列
    使用curl执行Http请求
  • 原文地址:https://blog.csdn.net/qq_16992475/article/details/127596596