天天看點

getway極簡落地入門1.為什麼使用網關2.實作3.配置oauth2的跨域

getway極簡落地入門1.為什麼使用網關2.實作3.配置oauth2的跨域

在spring cloud netflix時使用zuul作為官網,但是随着zuul2.0的多次跳票和getway異軍突起。getway已經是一款主流的産品了,同時springcloud alibaba官網的推薦網關也是getway,是以在選型時不需要猶豫。幹就完了。同時getway使用了webflux,較第一代網關更優秀。

1.為什麼使用網關

使用網關後,對于系統相當有了一個統一的入口,例如你有100個微服務系統,現在隻需要對外暴露網關的位址即可。同時所有的請求都是通過網關的分發,是以很友善的在網關上對請求攔截,重而實作反向代理,鑒權,流量控制,熔斷,日志監控等。

2.實作

getway基礎實作很簡單。鑒權等功能會在以後章節中釋出。

1.添加pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
複制代碼      
注意:getway使用的是webflux,不要引入spring-boot-starter-web

2.修改啟動類

@EnableDiscoveryClient
@SpringBootApplication
public class GetwayApplication {
 
    public static void main(String[] args) {
        //去除nacos日志
        System.setProperty("nacos.logging.default.config.enabled", "false");
        SpringApplication.run(GetwayApplication.class, args);
    }
 
}
複制代碼      

3.bootstrap.yml

getway也需要注冊到nacos中。也需要将namespace和group對應。

server:
  port: 6001 
spring:
  application:
    name: gateway-server
  cloud:
    nacos:
      discovery:
        # 服務注冊位址
        server-addr: 192.168.xx.xx:8848
        #命名空間
        namespace: b80f0aa4-3af2-a6e3-c6fda24c2bc0
        #分組
        group: xxx
      config:
        # 配置中心位址
        server-addr: 192.168.xx.xx:8848
        # 配置檔案格式
        file-extension: yml
        #命名空間
        namespace: b80f0aa4-3af2-a6e3-c6fda24c2bc0
        #分組
        group: xxx
    gateway:
      routes:
        # 路由辨別(id:辨別,具有唯一性) 
        - id: auth
          # 目标服務位址(uri:位址,請求轉發後的位址) 此處是nacos中服務名稱
          uri: lb://auth-server
          # 路由條件(predicates:斷言,比對 HTTP 請求内容)
          predicates:
            ## 當路徑為/auth/xx/xx的請求都會轉發到auth-server (也就是請求system-resource/auth/xx/xx)
            - Path=/auth/**
        - id: systemresource
          uri: lb://system-resource
          predicates:
            - Path=/system/**
複制代碼      

樓主因為在小公司,是以隻使用該規則就滿足了業務要求,如果有其他規則使用,請自行百度,這裡不具體介紹。

注意:
  1. getway隻能擷取同namespace和group中的服務。
  2. websocket接口與普通接口用以上配置就可以同時接受,不用額外配置路由。

3.配置oauth2的跨域

spring cloud ouath2 + getway跨域是有特别的配置的(與普通跨域不同)需要特别注意。

1.修改bootstrap.yml

spring:
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
        corsConfigurations:
          '[/**]':
            # 支援跨域通路的來源 也就是前台位址 可以配置多個 方法如下
            allowedOrigins:
              - "http://192.168.xx.xx:8080"
              - "http://192.168.xx.xx:8080"
            # 切記 allowCredentials 配置 為true時,allowedOrigins不能為 *
            allowCredentials: true
            maxAge: 86400
            # 支援的方法 * 代表所有
            allowedMethods: "*"
            allowedHeaders: "*"
            exposedHeaders: "setToken"
      routes:
        # 路由辨別(id:辨別,具有唯一性)   截取請求
        - id: auth
          # 目标服務位址(uri:位址,請求轉發後的位址)
          uri: lb://auth
          # 路由條件(predicates:斷言,比對 HTTP 請求内容)
          predicates:
            ## 轉發位址格式為 uri/archive,/str 部分會被下面的過濾器給截取掉
            - Path=/auth/**
複制代碼      

2.添加GatewayConfig

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
 
@Configuration
@EnableConfigurationProperties(GlobalCorsProperties.class)
public class GatewayConfig {
 
    /**
     * 配置全局解決cors跨域問題
     *
     * @return
     */
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @RefreshScope
    @Bean
    public CorsWebFilter corsWebFilter(GlobalCorsProperties globalCorsProperties){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        globalCorsProperties.getCorsConfigurations().forEach((k,v) -> source.registerCorsConfiguration(k, v));
        return new CorsWebFilter(source);
    }
}
複制代碼      
注意如果網關中添加了跨域配置,業務服務就不要添加了,否則就會報錯!