import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tianxia.alibaba.entity.CommonResult;
import com.tianxia.alibaba.entity.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 按资源名称限流 + 后续处理
* @author liqb
* @date 2023-05-26 15:06
*/
@RestController
public class RateLimitController {
/**
* SentinelResource配置(上)
* @author liqb
* @date 2023-05-26 22:06
* @return
*/
@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下,OK http://localhost:8401/byResource
超过上述,疯狂点击,返回了自己定义的限流处理信息,限流发生
{"code":444, "message":"com.alibaba.csp.sentinel.slots.block.flow.FlowException\t 服务不可用", "data":null}
额外问题
此时关闭问服务8401 -> Sentinel控制台,流控规则消失了
通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息
@RestController
public class RateLimitController {
...
/**
* 按照Url地址限流 + 后续处理
* @author liqb
* @date 2023-05-26 22:25
* @return
*/
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl() {
return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
}
}
上面兜底方案面临的问题
package com.tianxia.springcloud.myhandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tianxia.alibaba.entity.CommonResult;
/**
* @author: liqb
* @date: 2023-05-26 2:41
*/
public class CustomerBlockHandler {
public static CommonResult handlerException01(BlockException exception) {
return new CommonResult(4444,"按客戶自定义,global handlerException----1");
}
public static CommonResult handlerException02(BlockException exception) {
return new CommonResult(4444,"按客戶自定义,global handlerException----2");
}
}
@RestController
public class RateLimitController {
...
/**
* 客户自定义限流处理逻辑
* @author liqb
* @date 2023-05-26 22:42
* @return
*/
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class, // <-------- 自定义限流处理类
blockHandler = "handlerException02") // <-----------
public CommonResult customerBlockHandler() {
return new CommonResult(200,"按客戶自定义",new Payment(2020L,"serial003"));
}
}
启动微服务后先调用一次 - http://localhost:8401/rateLimit/customerBlockHandler。
然后,多次快速刷新http://localhost:8401/rateLimit/customerBlockHandler。
刷新后,我们自定义兜底方法的字符串信息就返回到前端。
注意:注解方式埋点不支持 private 方法。 官网
@SentinelResource 用于定义资源,并提供可选的异常处理和 fallback 配置项。** @SentinelResource** 注解包含以下属性: