sentinel和spring cloud gateway整合
注意: 控制台的改造這里我就不一一細說了。如果想了解的話可以到以下網址
https://www.cnblogs.com/dabenxiang/p/14376990.html
改造后的控制台gitee地址是:
https://gitee.com/gzgyc/sentinel-dashboard.git
背景介紹:
Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 模塊,此模塊中包含網關限流的規則和自定義 API 的實體和管理邏輯:
GatewayFlowRule
:網關限流規則,針對 API Gateway 的場景定制的限流規則,可以針對不同 route 或自定義的 API 分組進行限流,支持針對請求中的參數、Header、來源 IP 等進行定制化的限流。ApiDefinition
:用戶自定義的 API 定義分組,可以看做是一些 URL 匹配的組合。比如我們可以定義一個 API 叫my_api
,請求 path 模式為/foo/**
和/baz/**
的都歸到my_api
這個 API 分組下面。限流的時候可以針對這個自定義的 API 分組維度進行限流。
spring cloud gateway代碼配置
從 1.6.0 版本開始,Sentinel 提供了 Spring Cloud Gateway 的適配模塊,可以提供兩種資源維度的限流:
- route 維度:即在 Spring 配置文件中配置的路由條目,資源名為對應的 routeId
- 自定義 API 維度:用戶可以利用 Sentinel 提供的 API 來自定義一些 API 分組
pom.xml的依賴配置:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
application.yml的配置
server:
port: 8311
spring:
application:
name: sentinel-nacos-gateway
cloud:
gateway:
enabled: true
discovery:
locator:
lower-case-service-id: true
routes:
# Add your routes here.
- id: web
uri: http://127.0.0.1:8701
predicates:
- Path=/web/**
- id: user
uri: http://127.0.0.1:8701
predicates:
- Path=/user/**
sentinel:
transport:
port: 8719
dashboard: localhost:18080
上面的配置其實就是一些網關的配置:
/web/** 跳轉到 http://127.0.0.1:8701/web/** ,
/user/** 跳轉到http://127.0.0.1:8701/user/**
我們這邊把sentinel的相關規則直接持久化到nacos中,而sentinel的dashboard控制台也跟nacos整合一起:
sentinel的配置文件:
@Configuration
public class GatewayConfiguration {
private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
String serverAddr = "localhost:8848";
String groupId = "SENTINEL_GROUP";
String dataId = "sentinel-nacos-gateway-gateway-flow-rules";
String apiGatewayDataId = "sentinel-nacos-gateway-gateway-api";
String degradeDataId = "sentinel-nacos-gateway-degrade-rules";
static {
System.setProperty("csp.sentinel.app.type","1");
}
public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
// Register the block exception handler for Spring Cloud Gateway.
return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter() {
return new SentinelGatewayFilter();
}
@PostConstruct
public void doInit() {
initCustomizedApis();
initGatewayRules();
}
//從nacos上動態讀取api分組
private void initCustomizedApis() {
ReadableDataSource dataSource = new NacosDataSource(serverAddr, groupId, apiGatewayDataId, new Converter<String, Set<ApiDefinition>>() {
@Override
public Set<ApiDefinition> convert(String s) {
List<ApiPathDefinition> lists = JSONObject.parseArray(s, ApiPathDefinition.class);
Set<ApiDefinition> resultSet = new HashSet<>();
for (ApiPathDefinition apiPathDefinition : lists) {
resultSet.add(apiPathDefinition.toApiDefinition());
}
return resultSet;
}
});
GatewayApiDefinitionManager.register2Property(dataSource.getProperty());
}
private void initGatewayRules() {
//從nacos上動態讀取網關的流控規則
ReadableDataSource dataSource = new NacosDataSource(serverAddr, groupId, dataId, new Converter<String, Set<GatewayFlowRule>>() {
//把nacos讀到的信息,轉成List<FlowRule>
@Override
public Set<GatewayFlowRule> convert(String s) {
return JSONObject.parseObject(s, new TypeReference<Set<GatewayFlowRule>>() {
});
}
});
GatewayRuleManager.register2Property(dataSource.getProperty());
//從nacos上動態讀取降級規則
ReadableDataSource degradeDataSource = new NacosDataSource(serverAddr, groupId, degradeDataId, new Converter<String, List<DegradeRule>>() {
//把nacos讀到的信息,轉成List<FlowRule>
@Override
public List<DegradeRule> convert(String s) {
List<DegradeRule> degradeRules = JSONObject.parseObject(s, new TypeReference<List<DegradeRule>>() {
});
return degradeRules;
}
});
DegradeRuleManager.register2Property(degradeDataSource.getProperty());
}
}
API Gateway 端配置的重點:
API Gateway 端使用時只需注入對應的 SentinelGatewayFilter
實例以及 SentinelGatewayBlockExceptionHandler
實例即可。
與控制台整合的重點:
在 API Gateway 端,用戶只需要在原有啟動參數的基礎上添加如下啟動參數即可標記應用為 API Gateway 類型:
# 注:通過 Spring Cloud Alibaba Sentinel 自動接入的 API Gateway 整合則無需此參數
-Dcsp.sentinel.app.type=1
雖然我上面沒有加-Dcsp.sentinel.app.type=1,但是也可以通過System.setProperty方法添加環境變量
static {
System.setProperty("csp.sentinel.app.type","1");
}
動態讀取nacos上的配置:
-
initCustomizedApis
方法: 從nacos上動態讀取api分組的配置 -
initGatewayRules
方法: 1.從nacos上動態讀取網關的流控規則 2.nacos上動態讀取降級規則
sentinel網關的api講解:
ApiDefinition的講解
Set<ApiDefinition> definitions = new HashSet<>();
ApiDefinition api1 = new ApiDefinition("web")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem().setPattern("/web/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
definitions.add(api1);
GatewayApiDefinitionManager.loadApiDefinitions(definitions);
上面的這個是官方的api的例子,相當於的控制台的頁面如下的配置:
setMatchStrategy的參數:
SentinelGatewayConstants.URL_MATCH_STRATEGY_EXACT
: 精確SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX
: 前綴SentinelGatewayConstants.URL_MATCH_STRATEGY_REGEX
: 正則
GatewayFlowRule的api講解
網關限流規則 GatewayFlowRule
的字段解釋如下:
-
resource
:資源名稱,可以是網關中的 route 名稱或者用戶自定義的 API 分組名稱。 -
resourceMode
:規則是針對 API Gateway 的 route(RESOURCE_MODE_ROUTE_ID
)還是用戶在 Sentinel 中定義的 API 分組(RESOURCE_MODE_CUSTOM_API_NAME
),默認是 route。 注意這里: routeId:指的是:spring cloud gateway里面定義的routesId的, API 分組: 則是ApiDefinition定義的資源 -
grade
:限流指標維度,同限流規則的grade
字段。 -
count
:限流閾值 -
intervalSec
:統計時間窗口,單位是秒,默認是 1 秒。 -
controlBehavior
:流量整形的控制效果,同限流規則的controlBehavior
字段,目前支持快速失敗和勻速排隊兩種模式,默認是快速失敗。 -
burst
:應對突發請求時額外允許的請求數目。 -
maxQueueingTimeoutMs
:勻速排隊模式下的最長排隊時間,單位是毫秒,僅在勻速排隊模式下生效。、 -
paramItem:參數限流配置。若不提供,則代表不針對參數進行限流,該網關規則將會被轉換成普通流控規則;否則會轉換成熱點規則。其中的字段:
-
parseStrategy
:從請求中提取參數的策略,目前支持提取來源 IP(PARAM_PARSE_STRATEGY_CLIENT_IP
)、Host(PARAM_PARSE_STRATEGY_HOST
)、任意 Header(PARAM_PARSE_STRATEGY_HEADER
)和任意 URL 參數(PARAM_PARSE_STRATEGY_URL_PARAM
)四種模式。 -
fieldName
:若提取策略選擇 Header 模式或 URL 參數模式,則需要指定對應的 header 名稱或 URL 參數名稱。 -
pattern
:參數值的匹配模式,只有匹配該模式的請求屬性值會納入統計和流控;若為空則統計該請求屬性的所有值。(1.6.2 版本開始支持) -
matchStrategy
:參數值的匹配策略,目前支持精確匹配(PARAM_MATCH_STRATEGY_EXACT
)、子串匹配(PARAM_MATCH_STRATEGY_CONTAINS
)和正則匹配(PARAM_MATCH_STRATEGY_REGEX
)。(1.6.2 版本開始支持)
-
用戶可以通過 GatewayRuleManager.loadRules(rules)
手動加載網關規則,或通過 GatewayRuleManager.register2Property(property)
注冊動態規則源動態推送(推薦方式)。
自定義限流的處理方法:
默認被限流的時候會報下面這個錯:
如果我們想在被限流的時候返回自定義的響應,可以在 GatewayCallbackManager
注冊回調進行定制:
setBlockHandler
:注冊函數用於實現自定義的邏輯處理被限流的請求,對應接口為BlockRequestHandler
。默認實現為DefaultBlockRequestHandler
,當被限流時會返回類似於下面的錯誤信息:Blocked by Sentinel: FlowException
。
sentinel控制台界面展示:
api管理:這里對應的就是ApiDefinition的配置
流控規則:這里對應的就是GatewayFlowRule的配置
api類型:
-
Route ID: spring cloud gateway里面定義的routesId的,在
applicaiton.properties
中的spring.cloud.gateway.routes
里面。比如我們的配置:所以我們這里可以設置route ID是名字叫: web,user。
-
API 分組: ApiDefinition定義的資源。
網關的降級規則問題處理
一個請求的流程圖如下:
那么網關能知道下游客戶端報錯了。並且觸發熔斷降級嗎?
答:不知道。所以無法觸發熔斷降級。
解決思路:
代碼如下:
@Configuration
public class SentinelGlobalFilter implements GlobalFilter , Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse originalResponse = exchange.getResponse();
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
// get match route id
Route route = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
String id = route.getId();
// 500 error -> degrade
if (originalResponse.getRawStatusCode() == 500) {
Entry entry = null;
try {
// 0 token
entry = SphU.entry(id);
Tracer.traceEntry(new Exception("error"), entry);
} catch (BlockException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (entry != null){
entry.close();
}
}
}
return super.writeWith(body);
}
};
// replace response with decorator
return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
@Override
public int getOrder() {
return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
}
}
demo地址:
地址:https://gitee.com/gzgyc/sentinel-demo.git
模塊名:sentinel-gateway