简介
Spring Cloud Gateway是Spring Cloud官方推出的第二代网关框架,取代Zuul网关。网关作为流量的,在微服务系统中有着非常作用,网关常见的功能有路由转发、权限校验、限流控制等作用
Git地址
https://gitee.com/wqrzsy/lp-demo/tree/master/lp-springboot-gateway
更多demo请关注
springboot demo实战项目
java 脑洞
java 面试宝典
开源工具
项目分析
- 项目包含四个项目
- lp-eureka 注册服务中心
- lp-gateway 网关
- lp-test-service 提供测试服务
- lp-springboot-admin 监控
启动顺序 lp-eureka -> lp-gateway -> lp-springboot-admin -> lp-test-service
- lp-springboot-admin
Spring Boot Admin 用于监控基于 Spring Boot 的应用,它是在 Spring Boot Actuator 的基础上提供简洁的可视化 WEB UI。
详细 :
- lp-gateway
跨域的设置
/**
* 设置跨域
* @return
*/
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
// 判断是否是跨域请求
if (CorsUtils.isCorsRequest(request)) {
HttpHeaders requestHeaders = request.getHeaders();
ServerHttpResponse response = ctx.getResponse();
HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
HttpHeaders headers = response.getHeaders();
// 设置跨域属性
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders
.getAccessControlRequestHeaders());
if (requestMethod != null) {
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
}
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
// 判断是否是返回
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
自定义过滤器: 域名过滤器
添加GateWay域名到Request中给下流服务器使用
@Component
public class RealmNameGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
private static final Logger logger = LoggerFactory.getLogger(RealmNameGatewayFilterFactory.class);
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest host = exchange.getRequest().mutate().headers(httpHeaders -> {
URI requestURI = exchange.getRequest().getURI();
String realmName = requestURI.getHost();
Assert.notNull(realmName, "host 为空");
realmName = realmName + ":" + requestURI.getPort();
httpHeaders.add("realmName", realmName);
logger.info("headers:" + httpHeaders.toString());
}).build();
//将现在的request 变成 change对象
ServerWebExchange build = exchange.mutate().request(host).build();
return chain.filter(build);
};
}
}
分流,通过配置导向不同服务,并在转发时去掉导向标识
#配置路由
routes:
- id: service
#eureka上的服务名
uri: lb://LP-TEST-SERVICE
predicates:
- Path=/qa/**
filters:
# 去掉/qa/ 比如访问url是/qa/test 经过gateway后,后面服务拿到的就只有/test
- StripPrefix=1
# 设置默认过滤器,设置域名过滤器为默认过滤
default-filters:
- RealmName
2. 测试
http://localhost:8000/qa/test/swagger-ui.html
demo项目导入
PS :本项目使用了JDK11,主要导入的时候要先安装JDK11
参考: https://www.jianshu.com/p/cd0275a2f5fb
如果这篇文章对你有帮助请给个star