天天看點

SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

系列文章目錄

1. 項目介紹及環境配置

2. 短信驗證碼登入

3. 使用者資訊

4. MongoDB

5. 推薦好友清單/MongoDB叢集/動态釋出與檢視

6. 圈子動态/圈子互動

7. 即時通訊(基于第三方API)

8. 附近的人(百度地圖APi)

9. 小視訊

10.網關配置

11.背景管理

文章目錄

  • 系列文章目錄
  • 一、 問題分析
  • 二、 搭建網關工程
    • 1. 建立工程
    • 2. 導入依賴
    • 3. 配置引導類
    • 4. 添加配置檔案
    • 5. 跨域支援
    • 6. 測試
  • 三、 統一鑒權
    • 1. 添加配置檔案
    • 2. 自定義過濾器
    • 3. Postman
  • 四. 配置中心
    • 1. 添加bootstrap.yml配置
    • 2. 所有 bootstrap 配置

一、 問題分析

針對用戶端API層,需要配置叢集保證高可用,使用API網關解決以下問題:

  • 用戶端直接通路應用叢集
  • 通路叢集需要兼顧負載均衡和容錯
  • 多WEB層進行路由轉發,統一的攔截過濾處理
SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

API網關 有很多實作方式,我們通過SpringCloud Gateway實作,使用Nacos作為配置中心

二、 搭建網關工程

SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

1. 建立工程

根目錄建立

tanhua-gateway

檔案:

SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

2. 導入依賴

建立

tanhua-gateway/pom.xml

檔案:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>tanhua</artifactId>
        <groupId>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>tanhua-gateway</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!-- 監控檢查-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- nacos配置中心依賴支援 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

        <dependency>
            <groupId>com.itheima</groupId>
            <artifactId>tanhua-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>
           

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);
    }
}
           

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
           

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);
    }
}
           

6. 測試

SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

三、 統一鑒權

SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

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

           

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;
    }
}
           

3. Postman

SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

四. 配置中心

Nacos提供了注冊中心和配置管理的能力,使用Nacos可以快速實作服務發現、服務配置管理等需求
SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

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
           
SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

2. 所有 bootstrap 配置

SpringBoot交友APP項目實戰(詳細介紹+案例源碼) - 10.網關配置系列文章目錄一、 問題分析二、 搭建網關工程三、 統一鑒權四. 配置中心

Gitee倉庫位址(所有 bootstrap 配置): https://gitee.com/yuan0_0/tanhua_bootstrap.git