01-spring-cloud-sentinel-01-基本使用

sentinel基本使用

1.1 編程式

下面是啟動main方法,然后會創(chuàng)建限流規(guī)則initFlowRules()然后進入while循環(huán),代碼塊Thread.sleep(10)System.out.println("hello world")就是業(yè)務(wù)方法。然后entry = SphU.entry("HelloWorld")是使用了一個HelloWorld的資源。這個資源的限流模式再initFlowRules()里面已經(jīng)定義了。

public class MySentinelTest {
    public static void main(String[] args) {
        initFlowRules();
        while (true) {
            Entry entry = null;
            try {
                entry = SphU.entry("HelloWorld");
                /*您的業(yè)務(wù)邏輯 - 開始*/
                Thread.sleep(10);
                System.out.println("hello world");
                /*您的業(yè)務(wù)邏輯 - 結(jié)束*/
            } catch (BlockException | InterruptedException e) {
                /*流控邏輯處理 - 開始*/
                System.out.println("block!");
                /*流控邏輯處理 - 結(jié)束*/
            } finally {
                if (entry != null) {
                    entry.exit();
                }
            }
        }
    }

    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(20);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}

上面代碼執(zhí)行可以新建一個maven項目,然后導(dǎo)入sentinel依賴。由于現(xiàn)在spring主要推薦3.x所以無法再spring init上面創(chuàng)建jdk為1.8的項目。大家可以去alibaba上面創(chuàng)建空的項目。地址如下:https://start.aliyun.com/

1.2 注解式

第一步:創(chuàng)建一個controller層和service層。其中service層使用注解控制資源

controller層代碼

@RestController
public class MySentinelController {
    @Autowired
    private MySentinelService mySentinelService;

    @GetMapping("/helloworld")
    public String helloworld(){
        String message = mySentinelService.getInfo();
        return message;
    }
}

service層代碼

controller層會調(diào)用service的getInfo方法。再getInfo方法上面新增資源注解@SentinelResource(value = "helloworld",blockHandler = "blockMessage其中value是資源的名字,blockHandler是如果觸發(fā)限流,那么執(zhí)行什么方法。這個例子里面如果觸發(fā)限流會調(diào)用下面的blockMessage方法。主要這里的入?yún)⑿枰獣rBlockException

@Service
public class MySentinelService {
    @SentinelResource(value = "helloworld",blockHandler = "blockMessage")
    public String getInfo() {
        return "hello world sentinel";
    }

    public String blockMessage(BlockException e){
        System.out.println(e);
        return "阻塞了!";
    }
}

第二步:創(chuàng)建限流規(guī)則hellworld

springboot啟動類里面新增初始化限流規(guī)則的方法

@SpringBootApplication
public class LearningSentinelApplication {

    public static void main(String[] args) {
        SpringApplication.run(LearningSentinelApplication.class, args);
        initFlowRules();
    }

    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("helloworld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}

:::success

上面是一個簡單的sentinel入門程序,能夠讓我們看到sentinel的作用,也了解一些再sentinel里面的概念,比如:資源。下面是根據(jù)上面代碼整合sentinel提供的dashboard

:::

dashboard環(huán)境搭建

2.1 下載dashboard

可以去github下載

2.2 啟動dashboard

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.7.jar

2.3 訪問dashboard

地址:http://localhost:8080/#/login

默認賬號密碼:sentinel/sentinel

訪問結(jié)果:


image.png

2.4 項目接入dashboard

修改項目配置文件

# Sentinel 控制臺地址
spring.cloud.sentinel.transport.dashboard=localhost:8080
# 取消Sentinel控制臺懶加載
# 默認情況下 Sentinel 會在客戶端首次調(diào)用的時候進行初始化,開始向控制臺發(fā)送心跳包
# 配置 sentinel.eager=true 時,取消Sentinel控制臺懶加載功能
spring.cloud.sentinel.eager=true
# 如果有多套網(wǎng)絡(luò),又無法正確獲取本機IP,則需要使用下面的參數(shù)設(shè)置當前機器可被外部訪問的IP地址,供admin控制臺使用
# spring.cloud.sentinel.transport.client-ip=
server.port=8081
spring.application.name=learning_sentinel

spring boot啟動類去掉初始化限流規(guī)則

在spring啟動類中去掉限流規(guī)則??梢栽赿ashboard上面創(chuàng)建限流規(guī)則,然后再業(yè)務(wù)代碼中使用。后面也可以整合nacos通過nacos下發(fā)限流規(guī)則

    public static void main(String[] args) {
        SpringApplication.run(LearningSentinelApplication.class, args);
//        initFlowRules();
    }

2.5 啟動項目,在dashboard上面配置helloworld限流規(guī)則

image.png

整合nacos實現(xiàn)下發(fā)限流規(guī)則

3.1 下載nacos客戶端

可以去github上面下載

3.2 啟動nacos

啟動nacos

.\startup.cmd -m standalone

訪問地址

http://192.168.31.14:8848/nacos/index.html

3.3 修改項目配置

項目添加nacos依賴

        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>

修改項目配置文件

下面是配置項目里面的application.properties新增nacos地址,其中dataId一定要和配置的nacos保持一致,groupId也是一樣

spring.cloud.sentinel.datasource.ds.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.ds.nacos.dataId=learning-sentinel
spring.cloud.sentinel.datasource.ds.nacos.groupId=DEFAULT_GROUP

spring.cloud.sentinel.datasource.ds.nacos.ruleType=flow

3.4 在nacos上面新增流控配置

upload_eebb3a2dca99454f385e7152f058243d.png

其中json表示配置的資源和資源的流控規(guī)則

[
    {
        "resource": "helloworld",
        "limitApp": "default",
        "grade": 1,
        "count": 2,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容