輕鬆入門Sentinel

1.下載sentinel-dashboard

下載路徑:https://github.com/alibaba/Sentinel/releases/download/1.7.1/sentinel-dashboard-1.7.1.jar,也可以選擇需要的版本下載

如果GitHub下載過慢,進傳送門:

鏈接: https://pan.baidu.com/s/1NLruPccLq7E0Q66ZEFvNDA

提取碼: hsn2

2. 啟動sentinel-dashboard控制檯服務

<code>java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.7.1.jar/<code>

3. 登錄控制檯

http://127.0.0.1:8080/#/login,默認用戶名和密碼都是 sentinel

輕鬆入門Sentinel


輕鬆入門Sentinel


4.創建springboot maven項目sentinel-demo,可參考

5.引入pom依賴

<code><parent>
        <groupid>org.springframework.boot/<groupid>
        <artifactid>spring-boot-starter-parent/<artifactid>
        <version>2.2.4.RELEASE/<version>
    /<parent>
    <dependencies>
        <dependency>
            <groupid>org.springframework.boot/<groupid>
            <artifactid>spring-boot-starter-web/<artifactid>
        /<dependency>
        <dependency>
            <groupid>com.alibaba.cloud/<groupid>
            <artifactid>spring-cloud-starter-alibaba-sentinel/<artifactid>
            <version>2.2.0.RELEASE/<version>
        /<dependency>
    /<dependencies>/<code>

6. 創建啟動類App.java

<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}/<code>

7.創建配置文件application.yml

<code>server:
  #服務端口號
  port: 8090
spring:
  application:
    name: sentinel-demo
  cloud:
    sentinel:
      transport:
        #sentinel控制檯地址
        dashboard: 127.0.0.1:8080/<code>

8. 創建測試接口類SentinelDemoController.java

<code>import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelDemoController {

@SentinelResource(value = "testBlock",blockHandler = "blockHandlerMethod")
@GetMapping("/testBlock")
public String testBlock(){
return "限流方法測試,正常返回結果";
}

/**
* 限流執行方法
* */
public String blockHandlerMethod(BlockException be){
be.printStackTrace();
return "執行限流方法,被限流啦";
}

@SentinelResource(value = "testFallback",fallback = "fallbackMethod")
@GetMapping("/testFallback")
public String testFallback(int i){
double result=1/i;
return "降級方法測試,正常返回結果:"+result;
}


/**
* 降級執行方法
* */
public String fallbackMethod(int i){
return "執行降級方法,錯誤次數太多,請稍後再試";
}
}/<code>

9.測試流量控制

A. 啟動應用

B. 配置限流策略,這裡以QPS為例


輕鬆入門Sentinel

C. 達到流量限制,執行限流方法


輕鬆入門Sentinel

10.測試降級功能

A. 配置降級規則,這裡以錯誤次數為例


輕鬆入門Sentinel

B. 達到錯誤次數,執行降級方法


輕鬆入門Sentinel


分享到:


相關文章: