Spring Cloud Alibaba:Sentinel實現熔斷與限流

SpringBoot實戰電商項目mall(20k+star)地址:github.com/macrozheng/…java

摘要

Spring Cloud Alibaba 致力於提供微服務開發的一站式解決方案,Sentinel 做爲其核心組件之一,具備熔斷與限流等一系列服務保護功能,本文將對其用法進行詳細介紹。git

Sentinel簡介

隨着微服務的流行,服務和服務之間的穩定性變得愈來愈重要。 Sentinel 以流量爲切入點,從流量控制、熔斷降級、系統負載保護等多個維度保護服務的穩定性。github

Sentinel具備以下特性:web

  • 豐富的應用場景:承接了阿里巴巴近 10 年的雙十一大促流量的核心場景,例如秒殺,能夠實時熔斷下游不可用應用;
  • 完備的實時監控:同時提供實時的監控功能。能夠在控制檯中看到接入應用的單臺機器秒級數據,甚至 500 臺如下規模的集羣的彙總運行狀況;
  • 普遍的開源生態:提供開箱即用的與其它開源框架/庫的整合模塊,例如與 Spring Cloud、Dubbo、gRPC 的整合;
  • 完善的 SPI 擴展點:提供簡單易用、完善的 SPI 擴展點。您能夠經過實現擴展點,快速的定製邏輯。

安裝Sentinel控制檯

Sentinel控制檯是一個輕量級的控制檯應用,它可用於實時查看單機資源監控及集羣資源彙總,並提供了一系列的規則管理功能,如流控規則、降級規則、熱點規則等。spring

  • 咱們先從官網下載Sentinel,這裏下載的是sentinel-dashboard-1.6.3.jar文件,下載地址:github.com/alibaba/Sen…json

  • 下載完成後在命令行輸入以下命令運行Sentinel控制檯:bash

java -jar sentinel-dashboard-1.6.3.jar
複製代碼
  • Sentinel控制檯默認運行在8080端口上,登陸帳號密碼均爲sentinel,經過以下地址能夠進行訪問:http://localhost:8080

  • Sentinel控制檯能夠查看單臺機器的實時監控數據。

建立sentinel-service模塊

這裏咱們建立一個sentinel-service模塊,用於演示Sentinel的熔斷與限流功能。app

  • 在pom.xml中添加相關依賴,這裏咱們使用Nacos做爲註冊中心,因此須要同時添加Nacos的依賴:
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
複製代碼
  • 在application.yml中添加相關配置,主要是配置了Nacos和Sentinel控制檯的地址:
server:
 port: 8401
spring:
 application:
 name: sentinel-service
 cloud:
 nacos:
 discovery:
 server-addr: localhost:8848 #配置Nacos地址
 sentinel:
 transport:
 dashboard: localhost:8080 #配置sentinel dashboard地址
 port: 8719
service-url:
 user-service: http://nacos-user-service
management:
 endpoints:
 web:
 exposure:
 include: '*'
複製代碼

限流功能

Sentinel Starter 默認爲全部的 HTTP 服務提供了限流埋點,咱們也能夠經過使用@SentinelResource來自定義一些限流行爲。框架

建立RateLimitController類

用於測試熔斷和限流功能。ide

/** * 限流功能 * Created by macro on 2019/11/7. */
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {

    /** * 按資源名稱限流,須要指定限流處理邏輯 */
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handleException")
    public CommonResult byResource() {
        return new CommonResult("按資源名稱限流", 200);
    }

    /** * 按URL限流,有默認的限流處理邏輯 */
    @GetMapping("/byUrl")
    @SentinelResource(value = "byUrl",blockHandler = "handleException")
    public CommonResult byUrl() {
        return new CommonResult("按url限流", 200);
    }

    public CommonResult handleException(BlockException exception){
        return new CommonResult(exception.getClass().getCanonicalName(),200);
    }

}
複製代碼

根據資源名稱限流

咱們能夠根據@SentinelResource註解中定義的value(資源名稱)來進行限流操做,可是須要指定限流處理邏輯。

  • 流控規則能夠在Sentinel控制檯進行配置,因爲咱們使用了Nacos註冊中心,咱們先啓動Nacos和sentinel-service;

  • 因爲Sentinel採用的懶加載規則,須要咱們先訪問下接口,Sentinel控制檯中才會有對應服務信息,咱們先訪問下該接口:http://localhost:8401/rateLimit/byResource

  • 在Sentinel控制檯配置流控規則,根據@SentinelResource註解的value值:

  • 快速訪問上面的接口,能夠發現返回了本身定義的限流處理信息:

根據URL限流

咱們還能夠經過訪問的URL來限流,會返回默認的限流處理信息。

  • 在Sentinel控制檯配置流控規則,使用訪問的URL:

自定義限流處理邏輯

咱們能夠自定義通用的限流處理邏輯,而後在@SentinelResource中指定。

  • 建立CustomBlockHandler類用於自定義限流處理邏輯:
/** * Created by macro on 2019/11/7. */
public class CustomBlockHandler {

    public CommonResult handleException(BlockException exception){
        return new CommonResult("自定義限流信息",200);
    }
}
複製代碼
  • 在RateLimitController中使用自定義限流處理邏輯:
/** * 限流功能 * Created by macro on 2019/11/7. */
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {

    /** * 自定義通用的限流處理邏輯 */
    @GetMapping("/customBlockHandler")
    @SentinelResource(value = "customBlockHandler", blockHandler = "handleException",blockHandlerClass = CustomBlockHandler.class)
    public CommonResult blockHandler() {
        return new CommonResult("限流成功", 200);
    }

}
複製代碼

熔斷功能

Sentinel 支持對服務間調用進行保護,對故障應用進行熔斷操做,這裏咱們使用RestTemplate來調用nacos-user-service服務所提供的接口來演示下該功能。

  • 首先咱們須要使用@SentinelRestTemplate來包裝下RestTemplate實例:
/** * Created by macro on 2019/8/29. */
@Configuration
public class RibbonConfig {

    @Bean
    @SentinelRestTemplate
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
複製代碼
  • 添加CircleBreakerController類,定義對nacos-user-service提供接口的調用:
/** * 熔斷功能 * Created by macro on 2019/11/7. */
@RestController
@RequestMapping("/breaker")
public class CircleBreakerController {

    private Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class);
    @Autowired
    private RestTemplate restTemplate;
    @Value("${service-url.user-service}")
    private String userServiceUrl;

    @RequestMapping("/fallback/{id}")
    @SentinelResource(value = "fallback",fallback = "handleFallback")
    public CommonResult fallback(@PathVariable Long id) {
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    @RequestMapping("/fallbackException/{id}")
    @SentinelResource(value = "fallbackException",fallback = "handleFallback2", exceptionsToIgnore = {NullPointerException.class})
    public CommonResult fallbackException(@PathVariable Long id) {
        if (id == 1) {
            throw new IndexOutOfBoundsException();
        } else if (id == 2) {
            throw new NullPointerException();
        }
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    public CommonResult handleFallback(Long id) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"服務降級返回",200);
    }

    public CommonResult handleFallback2(@PathVariable Long id, Throwable e) {
        LOGGER.error("handleFallback2 id:{},throwable class:{}", id, e.getClass());
        User defaultUser = new User(-2L, "defaultUser2", "123456");
        return new CommonResult<>(defaultUser,"服務降級返回",200);
    }
}
複製代碼
  • 啓動nacos-user-service和sentinel-service服務:

  • 因爲咱們並無在nacos-user-service中定義id爲4的用戶,全部訪問以下接口會返回服務降級結果:http://localhost:8401/breaker/fallback/4

{
	"data": {
		"id": -1,
		"username": "defaultUser",
		"password": "123456"
	},
	"message": "服務降級返回",
	"code": 200
}
複製代碼

與Feign結合使用

Sentinel也適配了Feign組件,咱們使用Feign來進行服務間調用時,也可使用它來進行熔斷。

  • 首先咱們須要在pom.xml中添加Feign相關依賴:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
複製代碼
  • 在application.yml中打開Sentinel對Feign的支持:
feign:
 sentinel:
 enabled: true #打開sentinel對feign的支持
複製代碼
  • 在應用啓動類上添加@EnableFeignClients啓動Feign的功能;

  • 建立一個UserService接口,用於定義對nacos-user-service服務的調用:

/** * Created by macro on 2019/9/5. */
@FeignClient(value = "nacos-user-service",fallback = UserFallbackService.class)
public interface UserService {
    @PostMapping("/user/create")
    CommonResult create(@RequestBody User user);

    @GetMapping("/user/{id}")
    CommonResult<User> getUser(@PathVariable Long id);

    @GetMapping("/user/getByUsername")
    CommonResult<User> getByUsername(@RequestParam String username);

    @PostMapping("/user/update")
    CommonResult update(@RequestBody User user);

    @PostMapping("/user/delete/{id}")
    CommonResult delete(@PathVariable Long id);
}
複製代碼
  • 建立UserFallbackService類實現UserService接口,用於處理服務降級邏輯:
/** * Created by macro on 2019/9/5. */
@Component
public class UserFallbackService implements UserService {
    @Override
    public CommonResult create(User user) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"服務降級返回",200);
    }

    @Override
    public CommonResult<User> getUser(Long id) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"服務降級返回",200);
    }

    @Override
    public CommonResult<User> getByUsername(String username) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"服務降級返回",200);
    }

    @Override
    public CommonResult update(User user) {
        return new CommonResult("調用失敗,服務被降級",500);
    }

    @Override
    public CommonResult delete(Long id) {
        return new CommonResult("調用失敗,服務被降級",500);
    }
}
複製代碼
  • 在UserFeignController中使用UserService經過Feign調用nacos-user-service服務中的接口:
/** * Created by macro on 2019/8/29. */
@RestController
@RequestMapping("/user")
public class UserFeignController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public CommonResult getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }

    @GetMapping("/getByUsername")
    public CommonResult getByUsername(@RequestParam String username) {
        return userService.getByUsername(username);
    }

    @PostMapping("/create")
    public CommonResult create(@RequestBody User user) {
        return userService.create(user);
    }

    @PostMapping("/update")
    public CommonResult update(@RequestBody User user) {
        return userService.update(user);
    }

    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id) {
        return userService.delete(id);
    }
}
複製代碼
{
	"data": {
		"id": -1,
		"username": "defaultUser",
		"password": "123456"
	},
	"message": "服務降級返回",
	"code": 200
}
複製代碼

使用Nacos存儲規則

默認狀況下,當咱們在Sentinel控制檯中配置規則時,控制檯推送規則方式是經過API將規則推送至客戶端並直接更新到內存中。一旦咱們重啓應用,規則將消失。下面咱們介紹下如何將配置規則進行持久化,以存儲到Nacos爲例。

原理示意圖

  • 首先咱們直接在配置中心建立規則,配置中心將規則推送到客戶端;

  • Sentinel控制檯也從配置中心去獲取配置信息。

功能演示

  • 先在pom.xml中添加相關依賴:
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
複製代碼
  • 修改application.yml配置文件,添加Nacos數據源配置:
spring:
 cloud:
 sentinel:
 datasource:
 ds1:
 nacos:
 server-addr: localhost:8848
 dataId: ${spring.application.name}-sentinel
 groupId: DEFAULT_GROUP
 data-type: json
 rule-type: flow
複製代碼
  • 在Nacos中添加配置:

  • 添加配置信息以下:
[
    {
        "resource": "/rateLimit/byUrl",
        "limitApp": "default",
        "grade": 1,
        "count": 1,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]
複製代碼
  • 相關參數解釋:

    • resource:資源名稱;
    • limitApp:來源應用;
    • grade:閾值類型,0表示線程數,1表示QPS;
    • count:單機閾值;
    • strategy:流控模式,0表示直接,1表示關聯,2表示鏈路;
    • controlBehavior:流控效果,0表示快速失敗,1表示Warm Up,2表示排隊等待;
    • clusterMode:是否集羣。
  • 發現Sentinel控制檯已經有了以下限流規則:

  • 快速訪問測試接口,能夠發現返回了限流處理信息:

參考資料

Spring Cloud Alibaba 官方文檔:github.com/alibaba/spr…

使用到的模塊

springcloud-learning
├── nacos-user-service -- 註冊到nacos的提供User對象CRUD接口的服務
└── sentinel-service -- sentinel功能測試服務
複製代碼

項目源碼地址

github.com/macrozheng/…

公衆號

mall項目全套學習教程連載中,關注公衆號第一時間獲取。

公衆號圖片
相關文章
相關標籤/搜索