springboot整合sentinel接口熔斷的實現(xiàn)示例
背景
請求第三方接口或者慢接口需要增加熔斷處理,避免因為慢接口qps過大導致應用大量工作線程陷入阻塞以至于其他正常接口都不可用,最近項目測試環(huán)境就因為一個查詢的慢接口調(diào)用次數(shù)過多,導致前端整個首頁都無法加載。
依賴下載
springboot
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.3</version> </parent> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
sentinel dashboard
下載地址:
https://github.com/alibaba/Sentinel/releases
版本:
sentinel-dashboard-1.8.3.jar
啟動命令:
java -Dserver.port=9000 -Dcsp.sentinel.dashboard.server=localhost:9000 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.3.jar
sentinel springboot 依賴
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> <version>2021.0.1.0</version> </dependency>
熔斷嘗試
使用SentinelResource注解
編寫慢接口
@RestController
@RequestMapping(path = "/user")
@RequiredArgsConstructor
@Slf4j
public class UserCtrl {
private final IUserService userService;
@GetMapping("/{id}")
@SneakyThrows
@SentinelResource(value = "findById", fallback = "findByIdExt")
public User findById(@PathVariable("id") Long id) {
TimeUnit.SECONDS.sleep(3);
return userService.findById(id);
}
public User findByIdExt(Long id) {
log.error("觸發(fā)熔斷");
throw new IllegalStateException(String.format("id[{}]觸發(fā)熔斷", id));
}
}
應用注冊到sentinel dashboard
添加jvm啟動參數(shù):-Dcsp.sentinel.dashboard.server=${sentinel-dashboard域名}:9000
指定客戶端監(jiān)控 API 的端口(默認是 8719)-Dcsp.sentinel.api.port=8720

啟動應用,進行一次接口調(diào)用
Sentinel 會在客戶端首次調(diào)用的時候進行初始化,開始向控制臺發(fā)送心跳包。

配置熔斷規(guī)則


效果
快速調(diào)用3次慢接口,可以看到觸發(fā)熔斷


10秒熔斷失效后可再次成功訪問
不使用SentinelResource注解
慢接口代碼
@RestController
@RequestMapping(path = "/user")
@RequiredArgsConstructor
@Slf4j
public class UserCtrl {
private final IUserService userService;
@GetMapping("/{id}")
@SneakyThrows
public User findById(@PathVariable("id") Long id) {
TimeUnit.SECONDS.sleep(3);
return userService.findById(id);
}
}
配置熔斷規(guī)則


效果
快速訪問多次慢接口

對熔斷統(tǒng)一添加異常處理
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.test.test.model.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @description sentinel 降級處理
* @date 2024/6/14
*/
@Slf4j
public class WebBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
log.error(String.format("sentinel 降級 資源名稱%s", e.getRule().getResource()), e);
response.setContentType("application/json");
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.getWriter().print(JSON.toJSON(R.err(e.getMessage())));
}
}
import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.test.test.hanlder.WebBlockExceptionHandler;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @description
* @date 2024/6/14
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(SentinelFeignAutoConfiguration.class)
public class SentinelAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public BlockExceptionHandler blockExceptionHandler() {
return new WebBlockExceptionHandler();
}
}
統(tǒng)一降級異常處理效果


到此這篇關于springboot整合sentinel接口熔斷的實現(xiàn)示例的文章就介紹到這了,更多相關springboot sentinel接口熔斷內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Sentinel原理與SpringBoot整合實戰(zhàn)案例講解
- Springboot?中使用Sentinel的詳細步驟
- 在SpringBoot項目中使用Spring Cloud Sentinel實現(xiàn)流量控制
- springboot?整合sentinel的示例代碼
- 詳解Springboot集成sentinel實現(xiàn)接口限流入門
- SpringBoot2.0+阿里巴巴Sentinel動態(tài)限流實戰(zhàn)(附源碼)
- springboot整合sentinel的方法教程
- SpringBoot基于Sentinel在服務上實現(xiàn)接口限流
- 詳解SpringBoot Redis自適應配置(Cluster Standalone Sentinel)
- SpringBoot整合Sentinel啟動失敗及運行時常見錯誤總結
相關文章
Java實現(xiàn)Word文檔變量的添加與修改操作詳解
文檔變量以鍵值對的形式存儲在文檔的元數(shù)據(jù)中,通過在正文中插入域(Field)來引用這些變量,可以實現(xiàn)一處修改全局同步的效果,本文將介紹如何利用 Java 代碼,通過一個第三方的 Word 文檔處理庫,實現(xiàn)文檔變量的添加與修改操作,有需要的小伙伴可以了解下2026-05-05
詳解java實現(xiàn)簡單掃碼登錄功能(模仿微信網(wǎng)頁版掃碼)
這篇文章主要介紹了java實現(xiàn)簡單掃碼登錄功能(模仿微信網(wǎng)頁版掃碼),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-05-05
java語言描述Redis分布式鎖的正確實現(xiàn)方式
這篇文章主要介紹了java語言描述Redis分布式鎖的正確實現(xiàn)方式,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12
SpringBoot配置文件application.properties的使用
這篇文章主要介紹了SpringBoot配置文件application.properties的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

