天天看點

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

一:下載下傳、安裝、運作Sentinel

1.window

下載下傳:

           GitHub上面的官方下載下傳位址:Releases · alibaba/Sentinel · GitHub

          或 

sentinel-dashboard-1.7.0.jar

:百度網盤 請輸入提取碼 提取碼:0rlf

安裝:在Sentinel的jar包目錄位址欄中輸入cmd,點選回車打開DOS視窗,如下圖:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

 輸入

java -jar Sentinel的jar包名稱

,回車之後就啟動了Sentinel,如下圖:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

如果出現端口已經被占用的提示,那就需要指定端口啟動,即輸入

java -jar Sentinel的jar包名稱 --server.port=端口号

,點選回車就可以啟動sentinel了

通路:

在位址欄輸入

http://localhost:端口号(預設是8080)

就可以通路了,初始使用者名和密碼都是

sentinel

,如下圖:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

 進入操作台:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

 2.linux

下載下傳:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

啟動

執行 

nohup java -jar sentinel-dashboard-1.7.1.jar &

 指令,背景啟動 Sentinel 控制台。通過檢視 

nohup.out

 日志輸入,如果有如下内容,說明啟動成功:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

 二:添加項目

1.在 pom.xml 檔案中,引入相關依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>lab-46-sentinel-demo</artifactId>

    <dependencies>
        <!-- 實作對 SpringMVC 的自動化配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Sentinel 核心庫 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-core</artifactId>
            <version>1.7.1</version>
        </dependency>
        <!-- Sentinel 接入控制台 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
            <version>1.7.1</version>
        </dependency>
        <!-- Sentinel 對 SpringMVC 的支援 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-spring-webmvc-adapter</artifactId>
            <version>1.7.1</version>
        </dependency>
        <!-- Sentinel 對【熱點參數限流】的支援 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-parameter-flow-control</artifactId>
            <version>1.7.1</version>
        </dependency>
        <!-- Sentinel 對 Spring AOP 的拓展 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-annotation-aspectj</artifactId>
            <version>1.7.1</version>
        </dependency>
    </dependencies>

</project>
           

2.Sentinel 配置檔案

在 resources 目錄下,建立 Sentinel 自定義的sentinel.properties 配置檔案。内容如下:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

3.配置項目啟動端口。内容如下:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

4.Application

建立 Application.java 類,配置 

@SpringBootApplication

 注解即可。代碼如下:

package cn.iocoder.springboot.lab46.sentineldemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        // 設定系統屬性 project.name,提供給 Sentinel 讀取
        System.setProperty("project.name", "demo-application");

        // 啟動 Spring Boot 應用
        SpringApplication.run(Application.class, args);
    }

}
           

 5.SpringMvcConfiguration

在 cn.iocoder.springboot.lab46.sentineldemo.config 包下,建立 SpringMvcConfiguration 配置類,自定義 

sentinel-spring-webmvc-adapter

 提供的攔截器。代碼如下:

package cn.iocoder.springboot.lab46.sentineldemo.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebTotalInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcTotalConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SpringMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // Add Sentinel interceptor
//        addSentinelWebTotalInterceptor(registry);
        addSentinelWebInterceptor(registry);
    }

    private void addSentinelWebInterceptor(InterceptorRegistry registry) {
        // 建立 SentinelWebMvcConfig 對象
        SentinelWebMvcConfig config = new SentinelWebMvcConfig();
        config.setHttpMethodSpecify(true); // 是否包含請求方法。即基于 URL 建立的資源,是否包含 Method。
        // config.setBlockExceptionHandler(new DefaultBlockExceptionHandler()); // 設定 BlockException 處理器。
//        config.setOriginParser(new RequestOriginParser() { // 設定請求來源解析器。用于黑白名單控制功能。
//
//            @Override
//            public String parseOrigin(HttpServletRequest request) {
//                // 從 Header 中,獲得請求來源
//                String origin = request.getHeader("s-user");
//                // 如果為空,給一個預設的
//                if (StringUtils.isEmpty(origin)) {
//                    origin = "default";
//                }
//                return origin;
//            }
//
//        });

        // 添加 SentinelWebInterceptor 攔截器
        registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**");
    }

    private void addSentinelWebTotalInterceptor(InterceptorRegistry registry) {
        // 建立 SentinelWebMvcTotalConfig 對象
        SentinelWebMvcTotalConfig config = new SentinelWebMvcTotalConfig();

        // 添加 SentinelWebTotalInterceptor 攔截器
        registry.addInterceptor(new SentinelWebTotalInterceptor(config)).addPathPatterns("/**");
    }

}
           

 結構如下:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

6.GlobalExceptionHandler

在 cn.iocoder.springboot.lab46.sentineldemo.web 包下,建立 GlobalExceptionHandler 配置類,自定義 

sentinel-spring-webmvc-adapter

 提供的攔截器。代碼如下:

package cn.iocoder.springboot.lab46.sentineldemo.web;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice(basePackages = "cn.iocoder.springboot.lab46.sentineldemo.controller")
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = BlockException.class)
    public String blockExceptionHandler(BlockException blockException) {
        return "請求過于頻繁";
    }

}
           

 結構如下:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

7.DemoController

package cn.iocoder.springboot.lab46.sentineldemo.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @GetMapping("/echo")
    public String echo() {
        return "echo";
    }

    @GetMapping("/test")
    public String test() {
        return "test";
    }

    @GetMapping("/sleep")
    public String sleep() throws InterruptedException {
        Thread.sleep(100L);
        return "sleep";
    }

    // 測試熱點參數限流
    @GetMapping("/product_info")
    @SentinelResource("demo_product_info_hot")
    public String productInfo(Integer id) {
        return "商品編号:" + id;
    }

    // 手動使用 Sentinel 用戶端 API
    @GetMapping("/entry_demo")
    public String entryDemo() {
        Entry entry = null;
        try {
            // 通路資源
            entry = SphU.entry("entry_demo");

            // ... 執行業務邏輯

            return "執行成功";
        } catch (BlockException ex) {
            return "被拒絕";
        } finally {
            // 釋放資源
            if (entry != null) {
                entry.exit();
            }
        }
    }

    // 測試 @SentinelResource 注解
    @GetMapping("/annotations_demo")
    @SentinelResource(value = "annotations_demo_resource",
            blockHandler = "blockHandler",
            fallback = "fallback")
    public String annotationsDemo(@RequestParam(required = false) Integer id) throws InterruptedException {
        if (id == null) {
            throw new IllegalArgumentException("id 參數不允許為空");
        }
        return "success...";
    }

    // BlockHandler 處理函數,參數最後多一個 BlockException,其餘與原函數一緻.
    public String blockHandler(Integer id, BlockException ex) {
        return "block:" + ex.getClass().getSimpleName();
    }

    // Fallback 處理函數,函數簽名與原函數一緻或加一個 Throwable 類型的參數.
    public String fallback(Integer id, Throwable throwable) {
        return "fallback:" + throwable.getMessage();
    }

}
           

 8. 簡單測試

使用浏覽器,通路下 http://127.0.0.1:7070/ 位址,進入 Sentinel 控制台。此時,我們可以看到 

demo-application

 應用。如下圖所示:

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

使用浏覽器,通路下 http://127.0.0.1:8080/demo/echo 接口 10 次。然後點選 Sentinel 控制台的「實時監控」菜單,可以看到該接口的請求情況。如下圖所示: 

Sentinel簡單實作一:下載下傳、安裝、運作Sentinel 二:添加項目

 9.根據自己的需求設定:流量規則,降級規則,熱點規則,系統規則等。