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)。

原文地址:https://www.cnblogs.com/tenny-peng/p/13032631.html