统一网关Gateway 在SpringCloud中网关的实现包括两种:
不能有web起步依赖(springboot项目项目添加这两个依赖即可)
server:
port: 10010
spring:
application:
name: gateway
cloud:
nacos:
server-addr: 127.0.0.1:8848
gateway:
routes: #网关路由配置
- id: user-service #路由的id 自定义 只要唯一即可
uri: lb://userservice #路由的目标地址
predicates: #路由断言 判断请求是否符合规则
- Path=/user/**
-After=2017-01-20T17:42:47.789-07:00[America/Denver]
-Before=2017-01-20T17:42:47.789-07:00[America/Denver]
cloud:
nacos:
server-addr: 127.0.0.1:8848
gateway:
routes: #网关路由配置
- id: user-service #路由的id 自定义 只要唯一即可
uri: lb://userservice #路由的目标地址
predicates: #路由断言 判断请求是否符合规则
- Path=/user/**
filters:
- AddRequestHeader=Truth, Itcast is freaking #添加请求头 truth为key 后面为value
default-filters:
- AddRequestHeader=Truth, Itcast is freaking
default-filters 对所有的都生效
@Component
@Order(-1) //定义优先级
public class AuthorizeFilter implements GlobalFilter{
//exchange上下文跟
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// TODO Auto-generated method stub
//1.获取请求参数
ServerHttpRequest request = exchange.getRequest();
MultiValueMap<String, String> params = request.getQueryParams();
//2.获取参数中的authorization参数
String auth = params.getFirst("authorization");
//3 判断 是否放行
if ("admin".equals(auth)) {
//相当于在下一个请求连里面找到exchange 相当于放行
return chain.filter(exchange);
}
//5 否则拦截
//5.设置状态码 401
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
顺序
网关中加入以下配置
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 # 这次跨域检测的有效期