为什么需要网关?

网关的两种实现:

网关Getway------快速入门
步骤一
网关背身也是一个微服务,需要注册到nacos中去

步骤二

成功运行后
可以通过网关进行请求转发到对应服务。

流程如下:

路由断言工厂
网关路由可以配置的东西有如下。


spring中的11中基本的Predicate工厂


路由过滤器GatewayFilter


案例:

在userserver中获取到请求头的要用一个@RequestHeader注解,required = false表示可传可不传
java
/**
* 路径: /user/110
*
* @param id 用户id
* @return 用户
*/
@GetMapping("/{id}")
public User queryById(@PathVariable("id") Long id,@RequestHeader(value = "Truth",required = false) String truth) {
System.out.println(truth);
return userService.queryById(id);
}

全局过滤器GlobalFilter

案例2:

这里可以由两种方式设定过滤器顺序,注解和接口。
java
@Component
//@Order(-1) //过滤器的优先级,越小越高
public class AuthorizeFilter implements GlobalFilter , Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//1.获取请求参数
ServerHttpRequest request = exchange.getRequest();
MultiValueMap<String, String> queryParams = request.getQueryParams();
//2.获取参数中的authorization参数
String authorization = queryParams.getFirst("authorization");
//3.判断参数值是否等于admin
if("admin".equals(authorization)) {
//4.是,放行
return chain.filter(exchange);
}
//5.否,拦截
//5.1设置状态码
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
@Override
public int getOrder() {
return -1;
}
}
运行结果符合预期所示


过滤器执行顺序



网关的cors跨域配置


options请求就是CORS的询问请求。