功能
网关搭建
创建新module , 导入依赖
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.cloud
spring-cloud-starter-gateway
编写路由配置及nacos地址
server:
port: 10010
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848 # nacos地址
cluster-name: sh
gateway:
routes:
- id: user-service # 路由标识,必须唯一
uri: lb://userservice #路由的目标地址
predicates: #路由断言,判断请求是否符合规则
- Path=/user/**
- id: order-service
uri: lb://orderservice
predicates:
- Path=/order/**
断言工厂
过滤器工厂
添加过滤器
路由过滤器Filter
添加请求头
默认过滤器defauleFilter
默认过滤器将会对所有路径的路由都生效
全局过滤器GlobalFilter
现有需求:定义全局过滤器,拦截请求,判断请求参数是否符合条件:
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.lang.annotation.Annotation;
// @Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter,Order {
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//获取请求参数
ServerHttpRequest request = exchange.getRequest();
MultiValueMap params = request.getQueryParams();
//获取请求参数的authorization
String auth = params.getFirst("authorization");
// 判断参数是否等于admin
if("admin".equals(auth)){
//是,放行
return chain.filter(exchange);
}
//设置状态码
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//否,拦截
return exchange.getResponse().setComplete();
}
@Override
public int value() {
return -1;
}
@Override
public Class