springcloud组件sentinel持久化到nacos

  • Post author:
  • Post category:其他




springcloud组件sentinel持久化





sentinel下载地址





springcloud-sentinel代码链接gitee



前期准备:



sentinel启动:

端口:8858
用户名:nacos
密码:nacos

启动命令:
java -Dserver.port=8858 -Dsentinel.dashboard.auth.username=nacos -Dsentinel.dashboard.auth.password=nacos -jar /root/sentinel/sentinel-dashboard-1.8.0.jar



nacos配置文件



demo-sentinel-degrade-rule

(json格式)

[
  {
    "resource": "/demo/degrade",
    "limitApp": "default",
    "count": 1.0,
    "timeWindow": 5,
    "grade": 2,
    "minRequestAmount": 3,
    "slowRatioThreshold": 1.0,
    "statIntervalMs": 1000
  }
]



demo-sentinel-flow-rule

(json格式)

[
  {
    "resource":"/demo/flow",
    "controlBehavior":0,
    "count":2,
    "grade":1,
    "limitApp":"default",
    "strategy":0
  },
  {
    "resource":"/假数据",
    "controlBehavior":0,
    "count":2,
    "grade":1,
    "limitApp":"default",
    "strategy":0
  }
]



1.目录结构

在这里插入图片描述



2.maven依赖



springcloud-sentinel依赖

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <!-- Spring Dependencies -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.2.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR8</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>

            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.5.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>



demo-sentinel依赖

    <dependencies>
        <!-- web 启动器依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- springcloud sentinel启动器-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

        <!-- sentinel 持久化依赖 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>

        <!-- nacos 注册中心依赖 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>



3.统一响应格式

/**
 * @author 黔程似景
 * @description 统一返回格式
 * @date 2022/10/26 19:58
 * @blame 黔程似景
 **/
public class Result<T> {
    private Integer code;
    private String msg;
    private T data;

    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static Result error(Integer code, String msg){
        return new Result(code,msg);
    }
}



4.handler(异常监听)

/**
 * @author 黔程似景
 * @description sentinel控制异常监听
 * @date 2022/10/26 19:59
 * @blame 黔程似景
 **/
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    Logger log= LoggerFactory.getLogger(this.getClass());

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
        // getRule() 资源  规则的详细信息
        log.info("BlockExceptionHandler BlockException================"+e.getRule());

        Result r = null;

        if (e instanceof FlowException) {
            r = Result.error(100,"流控规则异常");

        } else if (e instanceof DegradeException) {
            r = Result.error(101,"降级规则异常");

        } else if (e instanceof ParamFlowException) {
            r = Result.error(102,"热点规则异常");

        } else if (e instanceof SystemBlockException) {
            r = Result.error(103,"系统规则异常");

        } else if (e instanceof AuthorityException) {
            r = Result.error(104,"授权规则异常");
        }

        //返回json数据
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), r);
    }
}



5.controller

/**
 * @author 黔程似景
 * @description 接口demo
 * @date 2022/10/25 22:01
 * @blame 黔程似景
 **/
@RestController
@RequestMapping("/demo")
public class DemoController {

    /**
     * 流控接口
     */
    @GetMapping("/flow")
    public Result flow(){
        return new Result(200 , "hello sentinel ! ! ! ");
    }

    /**
     * 服务降级
     */
    @GetMapping("/degrade")
    public Result degrade(){
        //必须存在异常,否则无法触发异常
        int i = 1/0;
        return new Result(200 , "hello sentinel ! ! !");
    }

}



6.配置文件application.yaml



配置自己的nacos和sentinel地址

server:
  port: 8300

spring:
  application:
    name: demo-sentinel
  cloud:
    sentinel:
      transport:
        # sentinel服务地址
        dashboard: 192.168.153.199:8858
      web-context-unify: true # 默认将调用链路收敛,导致链路流控失效
      datasource:
        flow-rule:
          nacos:
            # flow:流控、degrade:服务降级、param-flow:热点参数限流、system:系统保护、authority:授权规则
            rule-type: flow
            #nacos服务地址
            server-addr: 192.168.153.199:8848
            username: nacos
            password: nacos
            # nacos命名空间(public可以不写,其他的一定要写)
            namespace: sentinel
            # nacos配置的配置dataId
            dataId: demo-sentinel-flow-rule
        degrade-rule:
          nacos:
            # degrade:服务降级
            rule-type: degrade
            server-addr: 192.168.153.199:8848
            username: nacos
            password: nacos
            dataId: demo-sentinel-degrade-rule
            namespace: sentinel

    nacos:
      server-addr: 192.168.153.199:8848
      discovery:
        namespace: sentinel
        username: nacos
        password: nacos



7.启动类

/**
 * @author 黔程似景
 * @description sentinel 工程启动类
 * @date 2022/10/25 21:53
 * @blame 黔程似景
 **/
@SpringBootApplication
public class SentinelApplication {

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

}



8.启动测试



8.1 启动nacos

在这里插入图片描述



8.2 启动sentinel

在这里插入图片描述



8.3 启动demo-sentinel微服务



多访问几次访问端口:


http://localhost:8300/demo/degrade

在这里插入图片描述



一秒内多访问几次访问端口:


http://localhost:8300/demo/flow

在这里插入图片描述



刷新sentinel



在这里插入图片描述




9.更加深入了解规则参数请移步到sentinel



版权声明:本文为weixin_64007696原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。