简介
SpringCloud Gateway是spingcloud家族的产品,使用netty实现的高性能服务网关,用于替换netflix公司的zuul网关实现。
参考地址: https://spring.io/projects/spring-cloud
-
术语
-
工作原理
-
Route Predicate Factories
-
GatewayFilter
-
Http Timeout
示例
- 添加依赖配置
<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>
server:
port: 9000
spring:
application:
name: svc-gateway
cloud:
nacos:
discovery:
server-addr: 175.178.191.230:8848
gateway:
routes:
- id: svc-hotel-consume
uri: lb://svc-hotel-consumer
predicates:
- Path=/hotel/**
- 自定义异常返回处理:
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public WebExceptionHandler exceptionHandler() {
return new WebExceptionHandler() {
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
exchange.getResponse().getHeaders().set("Content-Type","application/json");
Map map = new HashMap();
map.put("status",400);
map.put("msg",ex.getMessage());
return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(map).getBytes())));
}
};
}
- GlobalFilter
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter globalFilter() {
return new GlobalFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.printf("global filter start\n");
Mono<Void> mono = chain.filter(exchange);
System.out.printf("global filter end\n");
return mono;
}
};
}
整合sentinel
- pom.xml 增加依赖配置
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
参考信息见sentinel官网:https://sca.aliyun.com/docs/2.2.x/user-guide/sentinel/advanced-guide/
- 增加sentinel dashboard 配置信息
spring:
cloud:
sentinel:
transport:
dashboard: 192.168.235.129:8080