Spring Cloud入门系列(十六)- 服务网关之Gateway
断言 predicates
官网参考文档:
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.
Predicate:这是一个Java8函数谓词。输入类型是Spring Framework ServerWebExchange。
这允许您匹配来自HTTP请求的任何内容,例如头或参数
(哦,你这该死的百度翻译,如果你再这样,我一定会拿靴子狠狠的踢你的屁股,相信我,我会的。)
有些秒杀的网址,配置好了之后,比如说三天后的秒杀活动,就可以配置一个After的pridicate。
这个路由只会在三天后指定的时间开启,在这之前都无法参加。
Fileter 过滤器
官网参考文档:
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gatewayfilter-factories
自定义过滤器(Global Filter)
编码实现:
package com.banana.springcloud.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.time.LocalDateTime;
/**
* @author layman
* @date 2021/1/20
*/
@Component
@Slf4j
public class MyGlobalFilter implements GlobalFilter, Ordered {
/**
* ServerWebExchange:服务网络交换器 ,存放着重要的请求-响应属性、请求实例和响应实例等等,有点像 Context上下文。
* 通过给定的GatewayFilterChain处理Web请求并且(可选)委托给下一个{WebFilter}
* @param exchange 当前服务器交换
* @param chain 提供了一种委托给下一个过滤器的方法
* @return {@code Mono<Void>} 指示请求处理何时完成
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("------------come in MyGlobalFilter----------------时间:"+ LocalDateTime.now());
//获取请求参数中的第一个参数
String username = exchange.getRequest().getQueryParams().getFirst("username");
if(username == null ){
log.info("------用户名为空,非法访问------");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
//放行,进入下个过滤器
return chain.filter(exchange);
}
/**
* 获取此对象的顺序值。
* <p>值越高,优先级越低。值越低,优先级越高。
* (在某种程度上),类似于Servlet {load on startup}值。
* <p>相同的顺序值,优先级会变得随意
* @return 顺序值
* @see java.lang.Integer#MIN_VALUE = 2147483648 最大优先级
* @see java.lang.Integer#MAX_VALUE = -2147483648 最小优先级
*/
@Override
public int getOrder() {
return 0;
}
}