一、介绍
Spring Cloud Gateway是Spring Cloud 的一个子项目,该项目基于Spring5.x
、SpringBoot2.x
技术版本进行编写,意在提供简单方便、可扩展的统一API路由管理方式。
二、Gateway相关概念
- Route(路由): 路由是网关的基本单元,由ID、URI、一组Predicate(断言),一组Filter(过滤器)组成,请求会根据断言进行转发,同时也会根据相关的过滤器进行处理。
- Predicate(断言):路由进行转发的条件,符合条件后会将请求转发到URI配置的路径,支持多种配置,参考Route Predicate Factories
- Filter(过滤器):路由在进行转发时需经过过滤器的处理,可以在过滤器中修改请求信息、响应内容等。参考GatewayFilter Factories
三、使用Spring Cloud Gateway
1.创建一个项目作为网关配置
2.在pom.xml中添加网关依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency>
3.在项目的application.yml中配置应用
注意:路由的配置会按照顺序进行适配,应将断言精确高的路由放置在上方
server:port:9000spring:application:name: gatewan-appcloud:gateway:routes:-id: baidu_routeuri: https://cn.bing.compredicates:- Query=param,baidufilters:- AddRequestParameter=param1,hello
4.启动项目,测试
5.最开始的请求

配置断言和经过拦截器处理后的请求

请求被转发到https://cn.bing.com并添加了param1参数
gateway基础配置结束,详情参照官方网址
四、网关配置跨域
提供SpringBoot配置跨域请求,对于跨域请参考浏览器同源策略及跨域
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.reactive.CorsWebFilter;import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;@ConfigurationpublicclassCorsConfig{@Beanpublic CorsWebFiltercorsWebFilter(){
UrlBasedCorsConfigurationSource source=newUrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration=newCorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);returnnewCorsWebFilter(source);}}
至此,跨域请求配置结束!