Sentinel之@SentinelResource注解

目录

搭建工程

按资源名称限定限流+后续处理 

安装URL地址限流+后续处理

兜底方法面临问题:

进一步说明:


搭建工程

首先启动Nacos和Sentinel成功!!!

在8401加上依赖:


    com.atguigu.springcloud
    cloud-api-commons
    ${project.version}

 
 

yml

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719  #默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口

management:
  endpoints:
    web:
      exposure:
        include: '*'

业务类:

@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 服务不可用");
    }
 

按资源名称限定限流+后续处理 

配置:

Sentinel之@SentinelResource注解_第1张图片

此时关闭微服务8401,Sentienl上的控制台上流控规则消失了,说明流控规则默认是临时结点!!!

安装URL地址限流+后续处理

编码:

@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl()
{
    return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
}
 

配置:

Sentinel之@SentinelResource注解_第2张图片

测试:

Sentinel之@SentinelResource注解_第3张图片

兜底方法面临问题:

Sentinel之@SentinelResource注解_第4张图片

自定义限流处理类:

public class CustomerBlockHandler {

    public static CommonResult handleException1(BlockException exception) {
        return new CommonResult(4444, "按客户自定义....exception1");

    }
    public static CommonResult handleException2(BlockException exception) {
        return new CommonResult(4444, "按客户自定义....exception2");

    }
}
 
 

 业务类:

@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
        blockHandlerClass = CustomerBlockHandler.class,
        blockHandler = "handlerException2")
public CommonResult customerBlockHandler()
{
    return new CommonResult(200,"按客戶自定义",new Payment(2020L,"serial003"));
}
 

进一步说明:

Sentinel之@SentinelResource注解_第5张图片

 好了,本篇的介绍就到此为止啦!!!

你可能感兴趣的:(SpringCloud,spring,cloud)