小編給大家分享一下Sentinel如何整合SpringCloud,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
Spring Cloud Alibaba Sentinel 是阿里巴巴提供的,致力于提供微服務一站式解決方案,Spring Cloud Alibaba 默認為 Sentinel 整合了,ServeLet、RestTemplate、FeignClient 和 Spring Flux。在 Spring 的生態中不僅不全了 Hystrix 在 ServeLet 和 RestTemplate 這一塊的空白,而且還完美的兼容了 Hystrix 在 Feign 中的限流降級用法,并支持運行時靈活的配置和調整限流降級規則。
引入依賴:
<!--Sentinel 整合SpringCloud 的依賴--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel</artifactId> <version>2.2.0.RELEASE</version> </dependency>
配置文件:
(入門使用中,應用名稱使用的 JVM 參數設置的,整合 SpringCloud 就不需要那樣了,配置文件中配置了應用的名稱后,Sentinel 會自動加載)
# 設置應用的名稱 spring: application: name: springCloudSentinel cloud: sentinel: transport: #設置Sentinel控制臺的主機地址和端口號 dashboard: localhost:9000
編寫測試 Controller ,控制臺添加 Sentinel_Cloud 資源 限流測試
@SentinelResource(value = "Sentinel_Cloud",blockHandler = "exceptionHandler") @GetMapping("/sentinelCloud") public String sentinelCloud(){ //使用限流規則 return "Sentinel_Cloud,成功調用"; }
限流時調用的方法:
/** * 定義降級 / 限流 的處理函數 * * @param exception * @return */ public String exceptionHandler(BlockException exception) { exception.printStackTrace(); return "Sentinel_Cloud,訪問限流"; }
Sentinel整合Feign (OpenFeign)
Sentinel適配了Feign組件。如果想要使用,除了引用spring-cloud-starter-alibaba-sentinel的依賴,還需要兩個步驟:
配置打開Sentinel對Feign的支持:feign.sentinel.enable=true
加入spring-cloud-starter-openfeign依賴使Sentinel starter自動化配置類生效。
# 設置應用的名稱 spring: application: name: springCloudSentinel cloud: sentinel: transport: #設置Sentinel控制臺的主機地址和端口號 dashboard: localhost:9000 # 開啟 Sentinel 對 Feign 的支持 feign: sentinel: enabled: true
服務端調用方Controller
@GetMapping("/feignHello") public String feignHello(){ return feignClient.feignHello(); }
服務提供方 FeignClient
@FeignClient(contextId = "testFeignClient", value = "注冊中心中服務的名稱", fallback = FeignFallbackService.class) public interface TestFeignClient { /** * OpenFeign 遠程調用的方法 * * @return */ @GetMapping("/test/feignHello") String feignHello(); }
提供一個 FeignClient 接口的實現類,作為限流的處理方法
@Service public class FeignFallbackService implements TestFeignClient{ @Override public String feignHello() { return "Feign 遠程調用限流了"; } }
Sentinel 控制臺添加限流規則:
請求方式:http://服務模塊注冊中心名稱/test/feignHello
以上是“Sentinel如何整合SpringCloud”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。