首页 > 文章列表 > Java @SentinelResource实例代码分析

Java @SentinelResource实例代码分析

java @SentinelResource
206 2023-04-28

Java @SentinelResource实例代码分析

按资源名称限流加后续处理

Module:cloudalibaba-sentinel-service8401

pom新增依赖

  <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->

            <groupId>com.atguigu.springcloud</groupId>

            <artifactId>cloud-api-common</artifactId>

            <version>${project.version}</version>

        </dependency>

这个依赖来自自己的模板,这里的这个依赖就是去数据库查询的一部分业务处理

新增Controller

@RestController

public class RateLimitController

{

    @GetMapping("/byResource")

    @SentinelResource(value = "byResource",blockHandler = "handleException")

    public CommonResult byResource()

    {

        return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));

    }

    public CommonResult handleException(BlockException exception)

    {

        return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");

    }

}

图形配置和代码关系

表示1秒钟内查询次数大于1,就跑到我们自定义的处流,限流

测试1

1秒钟点击1下,OK

超过上述,疯狂点击,返回了自己定义的限流处理信息,限流发生

按照Url地址限流加后续处理

通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息

Controller修改为:

@RestController

public class RateLimitController

{

    @GetMapping("/byResource")

    @SentinelResource(value = "byResource",blockHandler = "handleException")

    public CommonResult byResource()

    {

        return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));

    }

    public CommonResult handleException(BlockException exception)

    {

        return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");

    }

    @GetMapping("/rateLimit/byUrl")

    @SentinelResource(value = "byUrl")

    public CommonResult byUrl()

    {

        return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));

    }

}

测试2

访问一次

http://localhost:8401/rateLimit/byUrl

正常

疯狂点击http://localhost:8401/rateLimit/byUrl

会返回Sentinel自带的限流处理结果

上面兜底方案面临的问题

1 系统默认的,没有体现我们自己的业务要求。

2 依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。

3 每个业务方法都添加一个兜底的,那代码膨胀加剧。

4 全局统一的处理方法没有体现。

客户自定义限流处理逻辑

创建CustomerBlockHandler类用于自定义限流处理逻辑

测试后我们自定义的出来了

控制类增加新的业务

  @GetMapping("/rateLimit/customerBlockHandler")

    @SentinelResource(value = "customerBlockHandler",

            blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handleException2")

    public CommonResult customerBlockHandler()

    {

        return new CommonResult(200,"按客户自定义限流处理逻辑");

    }

自定义通用的限流处理逻辑

blockHandlerClass = CustomerBlockHandler.class

blockHandler = handleException2

上述配置:找CustomerBlockHandler类里的handleException2方法进行兜底处理 定义通用的限流处理逻辑

测试3

测试后我们自定义的出来了