官网地址:https://spring.io/projects/spring-cloud-gateway
中文文档参考:https://www.jianshu.com/p/6ff196940b67
Spring Cloud Gateway:提供网关服务
网关的核心作用:
- 路由匹配
可以进行服务匹配转发
cookie、header、path 等
- 过滤
实现请求的过滤处理
参数的非法校验、令牌校验、限流、非法请求拦截等
网关服务需要部署在外网服务器:对外。
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 28 29 30
| <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> <version>2.2.1.RELEASE</version> </dependency>
<dependency> <groupId>com.autohome</groupId> <artifactId>CarHome_Common</artifactId> <version>0.0.1-SNAPSHOT</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> </exclusion> </exclusions> </dependency>
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20200518</version> </dependency> </dependencies>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| server: port: 80 spring: application: name: gateway cloud: nacos: discovery: server-addr: 47.94.193.104:8848 gateway: discovery: locator: enabled: true lower-case-service-id: true routes: - id: gatewayapi uri: lb://api predicates: - Path=/car/** filters: - StripPrefix=1
|
1 2 3 4 5 6 7
| @SpringBootApplication @EnableDiscoveryClient public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class,args); } }
|
- 过滤器 - 根据实际情况修改过滤的内容:cookie、header、path 等
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| @Component @Slf4j public class VersionFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { log.info("过滤器----->");
ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.BAD_REQUEST); response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
if (request.getQueryParams().containsKey("version")) { double v = Double.parseDouble(request.getQueryParams().get("version").get(0)); log.info("过滤器----->版本号:" + v); if (v == 1.0) { return chain.filter(exchange); } else { DataBuffer dataBuffer = response.bufferFactory().wrap(new JSONObject(R.fail("当前版本不支持,请尽快升级")).toString().getBytes()); return response.writeWith(Mono.just(dataBuffer)); } } else { return chain.filter(exchange); } }
@Override public int getOrder() { return 1; } }
|