使用
Spring Cloud Gateway
作为API网关的一种实现,可以完成统一的权限校验、耗时统计、限流、计费等功能。类似功能产品有Zuul
(Nginx也有点类似)
快速体验
添加依赖
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
配置跳转
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//所有url都跳转到www.baidu.com
.route(r -> r.path("/**")
.uri("https://www.baidu.com")
)
.build();
}
}
访问体验
浏览器访问http://localhost:8080会显示百度首页内容
GlobalFilter
GlobalFilter只要注册到Spring容器,就可以应用在所有请求,比如监控请求耗时
定义全局Filter
ElapsedFilter.java
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.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Slf4j
@Component
public class ElapsedFilter implements GlobalFilter, Ordered {
private static final String ELAPSED_TIME_BEGIN = "elapsedTimeBegin";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
exchange.getAttributes().put(ELAPSED_TIME_BEGIN, System.currentTimeMillis());
return chain.filter(exchange).then(
Mono.fromRunnable(() -> {
Long startTime = exchange.getAttribute(ELAPSED_TIME_BEGIN);
if (startTime != null) {
log.info(exchange.getRequest().getURI().getRawPath() + ": cost " + (System.currentTimeMillis() - startTime) + "ms");
}
})
);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
访问http://localhost:8080/index.html可以在日志中看到所有请求的耗时情况
ps: ElapsedFilter
实现了GlobalFilter
接口
GatewayFilter
有的Filter并不希望应用在所有的URL上,比如权限校验,有的URL需要用户登录之后,有的不需要登录。这个时候就要会用GatewayFilter,可以配置到不同route规则上
定义网关接口
AuthFilter.java
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
@Component
public class AuthFilter implements GatewayFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getQueryParams().getFirst("authToken");
//返回401状态码和提示信息
if (StringUtils.isEmpty(token)) {
ServerHttpResponse response = exchange.getResponse();
JsonObject message = new JsonObject();
message.addProperty("status", -1);
message.addProperty("data", "鉴权失败");
byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bits);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
//指定编码,否则在浏览器中会中文乱码
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return -100;
}
}
GatewayApplication.java
@SpringBootApplication
public class GatewayApplication {
@Resource
private AuthFilter authFilter;
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/**")
.filters(f -> f.filter(authFilter)
.addRequestParameter("name", "tenmao")
)
.uri("https://www.qq.com")
)
.build();
}
}
参考
- Spring Cloud Gateway自定义Token校验过滤器
- Spring Cloud Gateway全局过滤器GlobalFilter:返回消息和重定向
- Spring Cloud(十四):Spring Cloud Gateway(过滤器)
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=30f2rka7np444