Sentinel?Gateway自定義限流返回結(jié)果方式
Sentinel Gateway自定義限流返回結(jié)果
sentinel在1.6.0后就引入了Sentinel API Gateway Adapter Common,適配了Gateway。
以前sentinel自定義限流結(jié)果是通過實現(xiàn)BlockExceptionHandler接口進行自定義限流返回結(jié)果,但是如果是使用了spring-cloud-alibaba-sentinel-gateway的依賴進行限流的話,使用之前的接口是不起作用的。
首先是我本地項目的環(huán)境,適配的是springboot 2.3.12.RELEASE版本,cloud版本為Hoxton.SR12。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>通過SentinelSCGAutoConfiguration配置類,我們可以看到主要有兩種方法可以實現(xiàn)自定義:配置文件配置和自定義代碼配置。
1、配置文件配置
在application.yml加入以下配置:
spring:
cloud:
sentinel:
scg:
fallback:
mode: response
responseBody: "{\"code\":\"429\",\"msg\":\"請求太多了\"}"對應(yīng)的配置類為FallbackProperties,以下是詳細(xì)的配置:
/** * The fallback mode for sentinel spring-cloud-gateway. choose `redirect` or * `response`. */ private String mode; /** * Redirect Url for `redirect` mode. */ private String redirect; /** * Response Body for `response` mode. */ private String responseBody; /** * Response Status for `response` mode. */ private Integer responseStatus = HttpStatus.TOO_MANY_REQUESTS.value(); /** * Content-Type for `response` mode. */ private String contentType = MediaType.APPLICATION_JSON.toString();
可以通過配置看到根據(jù)mode的類型處理模式有兩種:response和redirect。在SentinelSCGAutoConfiguration中對應(yīng)的代碼在 initFallback() 方法。
response:
如果設(shè)置mode為response則返回contentType 類型的responseBody,響應(yīng)碼為responseStatus 。
redirect:
如果設(shè)置mode為redirect,則限流后自動跳轉(zhuǎn)某個頁面,頁面地址為redirect。
2、自定義代碼配置
通過Sentinel wiki 我們可以看到:

所以我們可以通
過GatewayCallbackManager的 setBlockHandler() 方法來實現(xiàn)注冊我們自定義的異常處理類,需要實現(xiàn)BlockRequestHandler接口,默認(rèn)的異常處理類是:DefaultBlockRequestHandler。
首先自定義一個異常處理類:
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.List;
import static org.springframework.web.reactive.function.BodyInserters.fromValue;
/**
* @author TYH
* @Description: Sentinel異常處理類
* @date 2022/3/8 14:34
*/
public class SentinelBlockRequestHandler implements BlockRequestHandler {
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
// 判斷是否是html訪問,如果是則轉(zhuǎn)發(fā)url
if (acceptsHtml(exchange)) {
return htmlErrorResponse();
}
// 如果是接口訪問,則返回提示
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(fromValue(new ResponseData(HttpStatus.TOO_MANY_REQUESTS.value(),"請求太多了")));
}
private Mono<ServerResponse> htmlErrorResponse() {
String url="http://www.baidu.com";
URI uri =URI.create(url);
return ServerResponse.temporaryRedirect(uri).build();
}
private boolean acceptsHtml(ServerWebExchange exchange) {
try {
List<MediaType> acceptedMediaTypes = exchange.getRequest().getHeaders().getAccept();
acceptedMediaTypes.remove(MediaType.ALL);
MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
return acceptedMediaTypes.stream()
.anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
} catch (InvalidMediaTypeException ex) {
return false;
}
}
/**
* 定義返回的實體類,字段根據(jù)需要添加
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
static class ResponseData {
private int code;
private String msg;
}
}然后再調(diào)用GatewayCallbackManager的方法進行注冊:
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
/**
* @author TYH
* @Description:
* @date 2022/3/8 15:02
*/
@Slf4j
@Configuration
public class InitConfig implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("初始化限流handler");
GatewayCallbackManager.setBlockHandler(new SentinelBlockRequestHandler());
}
}
然后就實現(xiàn)了接口訪問限流返回固定值,html訪問限流跳轉(zhuǎn)頁面的效果。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于SpringBoot單元測試(cobertura生成覆蓋率報告)
這篇文章主要介紹了關(guān)于SpringBoot單元測試(cobertura生成覆蓋率報告),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
IKAnalyzer結(jié)合Lucene實現(xiàn)中文分詞(示例講解)
下面小編就為大家?guī)硪黄狪KAnalyzer結(jié)合Lucene實現(xiàn)中文分詞(示例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
SpringBoot詳細(xì)分析自動裝配原理并實現(xiàn)starter
相對于傳統(tǒng)意義上的Spring項目,SpringBoot具有開箱即用,簡化配置,內(nèi)置Tomcat等等等等一系列的特點。在這些特點中,最重要的兩條就是約定優(yōu)于配置和自動裝配2022-07-07
spring源碼學(xué)習(xí)之bean的初始化以及循環(huán)引用
這篇文章主要給大家介紹了關(guān)于spring源碼學(xué)習(xí)之bean的初始化以及循環(huán)引用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
將Mybatis升級為Mybatis-Plus的詳細(xì)過程
本文詳細(xì)介紹了在若依管理系統(tǒng)(v3.8.8)中將MyBatis升級為MyBatis-Plus的過程,旨在提升開發(fā)效率,通過本文,開發(fā)者可實現(xiàn)系統(tǒng)功能無損升級,同時享受MyBatis-Plus帶來的便捷特性,如代碼簡化和性能優(yōu)化,需要的朋友可以參考下2025-04-04
Spring security實現(xiàn)權(quán)限管理示例
這篇文章主要介紹了Spring security實現(xiàn)權(quán)限管理示例,這里整理了詳細(xì)的代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-01-01

