简介
Spring Cloud Gateway是Spring公司基于Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。它的目标是替代Netflflix,Zuul,其不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控和限流。
gateway快速入门
术语
Route: The basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates, and a collection of filters. A route is matched if the aggregate predicate is true.
Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange. This lets you match on anything from the HTTP request, such as headers or parameters.
Filter: These are instances of GatewayFilter that have been constructed with a specific factory. Here, you can modify requests and responses before or after sending the downstream request.
主要设置路由的id,uri路由的目标地址,以及路由的断言,以及过滤。
需要添加依赖
<!--引入gateway网关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
yml配置
server:
port: 8089
#配置应用的名字
spring:
application:
name: springcloud-gateway
cloud:
nacos:
discovery:
server-addr: 192.168.5.130:8848
gateway:
discovery:
locator:
enabled: true # 让gateway可以发现nacos中的微服务
### 此处我们配置我们自己订单模块,商品模块,用户模块的配置
routes: #路由数组[路由 就是指定当请求满足什么条件的时候转到哪个微服务]
##用户模块
- id: springcloud-order
uri: lb://springcloud-order #服务请求转发
#uri: http://localhost:8083 #服务请求转发
predicates:
- Path=/springcloud-order/**
##商品模块
- id: springcloud-product
uri: lb://springcloud-product #服务请求转发
predicates:
- Path=/springcloud-product/**
##用户模块
- id: springcloud-user
uri: lb://springcloud-user #服务请求转发
#uri: http://localhost:8081 #服务请求转发
predicates:
- Path=/springcloud-user/**
跨域配置
目前阶段因为都是本地本机开发不涉及跨域问题,如果服务部署在不通的服务器,就涉及跨域问题,网关可以统一的配置跨域访问问题。
@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);
}
}
其他配置 可以参考官网进行配置测试。