环境配置
一般gateway单独自己一个模块:
- 引入依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> </dependencies>
|
- 写application.yml文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| spring: application: name: gateway
cloud: nacos: discovery: server-addr: 127.0.0.1:8848
profiles: include: route
server: port: 80
|
- 写application-route.yml文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| spring: cloud: gateway: routes: - id: order uri: lb://service-order predicates: - Path=/api/order/**
- id: product uri: lb://service-product predicates: - Path=/api/product/**
|
断言
就是配置厚葬的predicates,需要满足条件才能通过gateway。
过滤器
将filter的配置放在于predicates同级的yml文件中:
1 2 3
| filters: - RewritePath=/api/order/?(?<segment>.*), /${segment} - OnceToken=X-Response-Token,jwt
|
GlobalFilter
GlobalFilter 通常,全局过滤器在网关层 用于 拦截所有请求,而局部过滤器用于单个路由。
eg:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @Component @Slf4j public class RTGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); String uri = request.getURI().toString(); long startTime = System.currentTimeMillis(); log.info("请求【{}】开始,时间{}", uri, startTime); Mono<Void> filter = chain.filter(exchange).doFinally(r -> { long endTime = System.currentTimeMillis(); log.info("请求【{}】结束,时间{},耗时:{}ms", uri, endTime, endTime - startTime); }); return filter; } @Override public int getOrder() { return 0; } }
|
自定义filter
遇到了再说
CORS-跨域处理
添加配置:
1 2 3 4 5 6 7 8 9 10 11 12 13
| spring: cloud: gateway: globalcors: cors-configurations: '[/**]': allowedOriginPatterns: '*' allowedHeaders: '*' allowedMethods: '*'
|