Spring Cloud Gateway簡單實例


概述

Spring Cloud Gateway旨在提供一種簡單而有效的方法來路由到API,並為它們提供跨領域的關注,例如:安全,權限,監控,限流等。

特性:

Spring Cloud Gateway的特性:

  • 基於 SpringFramework5、Project Reactor 和 SpringBoot2.0 構建
  • 能夠在任何請求屬性上匹配路由
  • 斷言和過濾器特定於路由
  • 集成 Hystrix 斷路器
  • 集成 Spring Cloud DiscoveryClient
  • 易於編寫斷言和過濾器
  • 請求速率限制
  • 路徑重寫

使用

1 項目pom添加依賴

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.2.5.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
      <dependency>
	      <groupId>org.springframework.boot</groupId>
	      <artifactId>spring-boot-starter-test</artifactId>
	      <scope>test</scope>
      </dependency>
	
      <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-config</artifactId>
      </dependency>
	
      <!-- 服務注冊/發現 -->
      <dependency>
	      <groupId>com.alibaba.cloud</groupId>
	      <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
      </dependency>
</dependencies>

<dependencyManagement>
      <dependencies>
            <dependency>
                  <groupId>org.springframework.cloud</groupId>
		  <artifactId>spring-cloud-dependencies</artifactId>
		  <version>Hoxton.SR3</version>
		  <type>pom</type>
		  <scope>import</scope>
	     </dependency>
		
	     <dependency>
		   <groupId>com.alibaba.cloud</groupId>
		   <artifactId>spring-cloud-alibaba-dependencies</artifactId>
		   <version>2.2.1.RELEASE</version>
		   <type>pom</type>
		   <scope>import</scope>
	      </dependency>
	</dependencies>
</dependencyManagement>

這里使用了nacos作為服務注冊中心和配置中心。

當然不用注冊中心和配置中心也可以。但是有了注冊中心,后面路由配置里的uri更靈活。另一方面,配置中心使得路由配置信息和項目分離,維護更方便。

關於nacos使用,可以參考我的另外一篇博客:nacos使用-服務注冊中心和配置中心

2 啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

沒什么特別,就是一個普通spring boot項目。

3 跨域配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;

@Configuration
public class CorsConfig {
	
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration();

        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
	
}

有了網關,就可以將跨域統一交給網關來做,原來的web服務則移除跨域配置。

4 路由配置

spring:
  cloud:
    gateway:
      routes:
        - id: order_route
          uri: lb://order-server
          predicates:
            - Path=/orderApi/**
          filters:
            - RewritePath=/orderApi/(?<segment>.*),/$\{segment}
			
        - id: product_route
          uri: lb://product-server
          predicates:
            - Path=/productApi/**
          filters:
            - RewritePath=/productApi/(?<segment>.*),/$\{segment}
        	
        #...省略其他配置項

這里的lb://order-server表示從服務注冊中心獲取名為order-server的服務,並且使用負載均衡的方式去訪問。

如果第一步沒有配置注冊中心,這里就只能寫死轉發地址了。

5 訪問

設網關服務端口server.port=8888

瀏覽器訪問localhost:8888/orderApi/order/info/1,網關會將其轉發到order-server/order/info/1

而這個order-server是從服務注冊中心獲取的。假設其實際注冊有兩個服務,地址分別為localhost:8081localhost:8082。則上面的請求最終會轉到localhost:8081/order/info/1localhost:8082/order/info/1

總結

Spring Cloud Gateway使用簡單。其項目也是一個spring boot項目,引入依賴,配置路由即可。

其他高級使用,如自定義Filter,集成Hystrix等,等我學會了,學會了就寫(立個flag XD)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM