• SpringBoot交友APP项目实战(详细介绍+案例源码) - 10.网关配置


    系列文章目录

    1. 项目介绍及环境配置
    2. 短信验证码登录
    3. 用户信息
    4. MongoDB
    5. 推荐好友列表/MongoDB集群/动态发布与查看
    6. 圈子动态/圈子互动
    7. 即时通讯(基于第三方API)
    8. 附近的人(百度地图APi)
    9. 小视频
    10.网关配置
    11.后台管理



    一、 问题分析

    针对客户端API层,需要配置集群保证高可用,使用API网关解决以下问题:

    • 客户端直接访问应用集群
    • 访问集群需要兼顾负载均衡和容错
    • 多WEB层进行路由转发,统一的拦截过滤处理

    在这里插入图片描述

    API网关 有很多实现方式,我们通过SpringCloud Gateway实现,使用Nacos作为配置中心

    二、 搭建网关工程

    在这里插入图片描述

    1. 创建工程

    根目录新建 tanhua-gateway 文件:
    在这里插入图片描述

    2. 导入依赖

    新建 tanhua-gateway/pom.xml 文件:

    
    <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>tanhuaartifactId>
            <groupId>com.itheimagroupId>
            <version>1.0-SNAPSHOTversion>
        parent>
        <modelVersion>4.0.0modelVersion>
    
        <artifactId>tanhua-gatewayartifactId>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-starter-gatewayartifactId>
            dependency>
    
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
            dependency>
    
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-actuatorartifactId>
            dependency>
    
            
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
            dependency>
    
            <dependency>
                <groupId>com.itheimagroupId>
                <artifactId>tanhua-commonsartifactId>
                <version>1.0-SNAPSHOTversion>
            dependency>
        dependencies>
    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

    3. 配置引导类

    新建 tanhua-gateway/src/main/java/com/tanhua/gateway/GatewayApplication.java 文件:

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

    4. 添加配置文件

    新建 tanhua-gateway/src/main/resources/application.yml 文件:

    server:
      port: 8888
    spring:
      profiles:
        active: prod
      application:
        name: tanhua-gateway
      cloud:
        # 配置注册中心
        nacos:
          discovery:
            server-addr: 192.168.136.160:8848
        gateway:
          globalcors:
            add-to-simple-url-handler-mapping: true
            corsConfigurations:
              '[/**]':
                allowedHeaders: "*"
                allowedOrigins: "*"
                allowedMethods:
                  - GET
                  - POST
                  - DELETE
                  - PUT
                  - OPTION
          # 配置路由
          routes:
            # 探花系统
            - id: tanhua-app-server
              uri: lb://tanhua-app-server
              predicates:
                - Path=/app/**
              filters:
                - StripPrefix= 1
            # 后台系统
            - id: tanhua-admin
              uri: lb://tanhua-admin
              predicates:
                - Path=/admin/**
              filters:
                - StripPrefix= 1
    
    • 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

    5. 跨域支持

    新建 tanhua-gateway/src/main/java/com/tanhua/gateway/config/CorsConfig.java 文件:

    /**
     * 跨域支持
     */
    @Configuration
    public class CorsConfig {
    
        @Bean
        public CorsWebFilter corsFilter() {
            CorsConfiguration config = new CorsConfiguration();
            config.addAllowedMethod("*");
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
            UrlBasedCorsConfigurationSource source =
                    new UrlBasedCorsConfigurationSource(new PathPatternParser());
            source.registerCorsConfiguration("/**", config);
            return new CorsWebFilter(source);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    6. 测试

    在这里插入图片描述


    三、 统一鉴权

    在这里插入图片描述

    1. 添加配置文件

    编辑 tanhua-gateway/src/main/resources/application.yml 文件:

    server:
      port: 8888
    spring:
      profiles:
        active: prod
      application:
        name: tanhua-gateway
      cloud:
        # 配置注册中心
        nacos:
          discovery:
            server-addr: 192.168.136.160:8848
        gateway:
          globalcors:
            add-to-simple-url-handler-mapping: true
            corsConfigurations:
              '[/**]':
                allowedHeaders: "*"
                allowedOrigins: "*"
                allowedMethods:
                  - GET
                  - POST
                  - DELETE
                  - PUT
                  - OPTION
          # 配置路由
          routes:
            # 探花系统
            - id: tanhua-app-server
              uri: lb://tanhua-app-server
              predicates:
                - Path=/app/**
              filters:
                - StripPrefix= 1
            # 后台系统
            - id: tanhua-admin
              uri: lb://tanhua-admin
              predicates:
                - Path=/admin/**
              filters:
                - StripPrefix= 1
    gateway:
      excludedUrls: /user/login,/user/loginVerification,/system/users/verification,/system/users/login
    
    
    • 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

    2. 自定义过滤器

    新建 tanhua-gateway/src/main/java/com/tanhua/gateway/filters/AuthFilter.java 文件:

    @Component
    public class AuthFilter implements GlobalFilter, Ordered {
    
        @Value("${gateway.excludedUrls}")
        private List<String> excludedUrls; //需要配置不校验的连接
    
        //过滤器核心业务代码
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            //1、排除不需要权限检验的连接
            String path = exchange.getRequest().getURI().getPath(); //当前请求连接
            if(excludedUrls.contains(path)) {
                return chain.filter(exchange);
            }
            //2、获取token并校验 (xxxxxx , Bearer xxxxx)
            String token = exchange.getRequest().getHeaders().getFirst("Authorization");
            if(!StringUtils.isEmpty(token)) {
                token = token.replaceAll("Bearer ","");
            }
            boolean verifyToken = JwtUtils.verifyToken(token);
            //3、如果检验失败,相应错误状态:401
            if(!verifyToken) {
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("errCode", 401);
                responseData.put("errMessage", "用户未登录");
                return responseError(exchange.getResponse(),responseData);
            }
            return chain.filter(exchange);
        }
    
        //响应错误数据
        private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
            // 将信息转换为 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] data = new byte[0];
            try {
                data = objectMapper.writeValueAsBytes(responseData);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            // 输出错误信息到页面
            DataBuffer buffer = response.bufferFactory().wrap(data);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
    
        //配置执行顺序
        public int getOrder() {
            return Ordered.LOWEST_PRECEDENCE;
        }
    }
    
    • 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

    3. Postman

    在这里插入图片描述

    四. 配置中心

    Nacos提供了注册中心和配置管理的能力,使用Nacos可以快速实现服务发现、服务配置管理等需求

    在这里插入图片描述

    1. 添加bootstrap.yml配置

    !!! 删除 application.yml 文件
    新建 tanhua-gateway/src/main/resources/bootstrap.yml 文件:

    spring:
      profiles:
        # active: prod
        active: dev
      application:
        name: tanhua-gateway
      cloud:
        nacos:
          discovery:
            server-addr: 192.168.136.160:8848
          config:
            server-addr: 192.168.136.160:8848
            file-extension: yml
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述

    2. 所有 bootstrap 配置

    在这里插入图片描述
    Gitee仓库地址(所有 bootstrap 配置): https://gitee.com/yuan0_0/tanhua_bootstrap.git

  • 相关阅读:
    动态规划问题——大盗阿福
    OpenCV-图像基础处理
    【洛谷题解/AcWing题解/NOIP2006提高组】P1064/AcWing481 金明的预算方案
    【Swin Transformer原理和源码解析】Hierarchical Vision Transformer using Shifted Windows
    openGauss亮相1024程序员节,深度解读openGauss 5.1.0版本
    macos13 arm芯片(m2) 搭建hbase docker容器 并用flink通过自定义richSinkFunction写入数据到hbase
    上转换纳米颗粒修饰二硫化钼纳米片|聚多巴胺修饰的二硫化钼纳米片(MoS2-PDA)|PEG聚乙二醇包裹二硫化钼纳米片(MoS2-PEG)
    Zynq中断与AMP~双核串口环回之PS与PL通信
    同义词替换-批量自动同义词替换软件
    zabbix集成openldap认证
  • 原文地址:https://blog.csdn.net/weixin_45137565/article/details/127557353