Article directory
Introduction to Gateway
Gateway is a gateway component in Spring Cloud, Spring Cloud Gateway aims to provide a simple and efficient way to route to APIs. Spring Cloud uses Zuul gateway in version 1.x, but uses Gateway instead of Zuul in version 2.x. Zuul is a Servlet-based implementation and belongs to blocking programming. SpringCloudGateway is based on WebFlux provided in Spring5, which belongs to the implementation of reactive programming and has better performance.
The function of the gateway
- Authentication and permission verification for user requests
- Route user requests to microservices and implement load balancing
- Limit user requests
Build Gateway
1. Create a Spring Boot project
2. Import gateway and nacos dependencies
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
3. Write routing configuration and nacos address
server:
port: 10010 #网关端口
spring:
application:
name: gateway #服务名称
cloud:
nacos:
server-addr: localhost:8848 #nacos地址
gateway:
routes: #网关路由配置
- id: user-service #路由id,保证唯一
uri: lb://userservice #路由的目标地址,lb就是负载均衡,后面跟服务名称
predicates: #路由断言,也就是判断请求是否符合路由规则的条件
- Path=/user/** #这个是按照路径匹配,只要以/user/开头就符合要求
- id: order-service
uri: lb://orderservice
predicates:
- Path=/order/**
4. Start
5. Test
Route Assertion Factory
The routing assertions filled in the predicates in the gateway configuration file will be read and processed by the Predicate Factory, and then turned into conditions for routing judgment. Spring Cloud provides us with twelve assertion factories
Each assertion factory official documentation provides examples
name | illustrate | Example |
---|---|---|
After | is a request after a certain point in time | - After=2037-01-20T17:42:47.789-07:00[America/Denver] |
Before | is a request before a certain point in time | - Before=2031-04-13T15:14:47.433+08:00[Asia/Shanghai] |
Between | is a request before a certain point in time | - Between=2037-01-20T17:42:47.789-07:00[America/Denver], 2037-01-21T17:42:47.789-07:00[America/Denver] |
Cookie | The request must contain certain cookies | - Cookie=chocolate, ch.p |
Header | The request must contain certain headers | - Header=X-Request-Id, \d+ |
Host | The request must be to access a certain host (domain name) | - Host=**.somehost.org,**.anotherhost.org |
Method | The request method must be the specified method | - Method=GET,POST |
Path | The request path must conform to the specified rules | - Path=/red/{segment},/blue/** |
Query | Request parameters must contain the specified parameters | - Query=name, Jack or - Query=name |
RemoteAddr | The requester's ip must be in the specified range | - RemoteAddr=192.168.1.1/24 |
Weight | Weight handling | - Weight=group1, 2 |
route filter
GatewayFilter is a filter provided in the gateway, which can process requests entering the gateway and responses returned by microservices.
Spring provides 31 different routing filter factories ( document addresses )
spring:
cloud:
gateway:
routes:
- id: lb://userservice
uri: https://example.org
predicates:
- Path=/user/**
filters: #过滤器(与id同级)
- AddRequestHeader=X-Request-red, blue#添加请求头
If you want to take effect for all routes, you can write the filter factory under default
spring:
cloud:
gateway:
routes:
#路由1
#路由2
#...
default-filters: #与routes同级
- AddResponseHeader=X-Response-Default-Red, Default-Blue
- PrefixPath=/httpbin
global filter
The role of the global filter is to process all requests and microservice responses that enter the gateway, just like the GatewayFilter. The difference is that GatewayFilter is defined by configuration, and the processing logic is fixed. The logic of GlobalFilter needs to be implemented by writing its own code. It is defined by implementing the GlobalFilter interface.
【Case】
Define a global filter, intercept requests, and determine whether the parameters of the request meet the following conditions:
1. Whether there is authorization in the parameters,
2. Whether the value of the authorization parameter is admin. Release if both are satisfied, otherwise intercept
//指定Order值得第一种方式使用注解
//指定Order值得第二种方式实现Ordered接口重写getOrder方法
//@Order(-1)//值越小优先执行
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
/**
* @param exchange:请求上下文,里面可以获取Request、Response等信息
* @param chain:用来把请求委托给下一个过滤器
* @return {@code Mono<Void>} 返回标示当前过滤器业务结束
*/
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//获取请求参数
ServerHttpRequest request = exchange.getRequest();
MultiValueMap<String, String> queryParams = request.getQueryParams();
//获取参数中的authorization参数
String auth = queryParams.getFirst("authorization");
//校验参数值是否等于admin
if ("admin".equals(auth)){
//是,放行
return chain.filter(exchange);
}
//否,拦截
//设置状态码
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//401未登录
return exchange.getResponse().setComplete();
}
@Override
public int getOrder() {
return -1;
}
}
test
filter execution order
- Each filter must specify an order value of type int. The smaller the order value, the higher the priority and the higher the execution order.
- GlobalFilter specifies the order value by implementing the Ordered interface, or adding the @Order annotation
- The order of the route filter and defaultFilter is specified by Spring, and the default is to increase from 1 according to the declaration order.
- When the order value of the filter is the same, it will be executed in the order of defaultFilter > Route Filter > GlobalFilter.
Handling cross-domain issues
Cross-domain problem: The browser prohibits the originator of the request from cross-domain with the serverajax request, the request is blocked by the browser
spring:
cloud:
gateway:
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: # 允许哪些网站的跨域请求
- "http://localhost:8090"
- "http://www.leyou.com"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期