入门教程流程

使用

1 添加Maven依赖

       
        
            com.alibaba.csp
            sentinel-core
            1.7.1
        

             
        
            com.alibaba.csp
            sentinel-transport-simple-http
            1.7.1
        

2 启动Sentinel控制台,非必选项,但一般都会使用

  • 首先下载Sentinel控制台的jar包,下载当前sentinel对应的版本:https://github.com/alibaba/Sentinel/releases
  • 然后运行,可以看到是个Spring Boot应用
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar ~/Downloads/sentinel-dashboard-1.7.1.jar

3 写sentinel的代码

import java.util.ArrayList;
import java.util.List;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

public class HelloSentinel {
    public static void main(String[] args) throws InterruptedException {
        initRules();

        while (true){
            try (Entry entry = SphU.entry("HelloWorld")) {
                Thread.sleep(10);
                // 业务逻辑
                System.out.println("hello world");
            } catch (BlockException e) {

                // 处理被拒绝的请求
                System.err.println("blocked");
            }
        }
    }

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

4 启动HelloSentinel项目,并且加上启动VM参数

-Dcsp.sentinel.dashboard.server=127.0.0.1:8080

5 去控制台看一下效果,当然也可以看日志,只是不够直观。

  • 日志位置:~/logs/csp/${appName}-metrics.log.{date}
image
  • 看控制台数据,地址为启动时指定的ip和端口:http://127.0.0.1:8080/。 账号和密码都为:sentinel

你可能感兴趣的:(入门教程流程)