1、按资源名称限流
- 控制器
@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" + "服务不可用");
}
}
- 配置流控:
- 访问测试:
2、按URL限流
- 控制器
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl(){
return new CommonResult(200, "按URL限流测试OK", new Payment(2020L, "serial002"));
}
- 配置流控
- 访问测试
按url限流不会调用自定义的异常方法,而是默认的提示
3、自定义全局限流
- 自定义全局限流类
public class CustomerBlockHandle {
public static CommonResult handleException(BlockException exception){
return new CommonResult(4444, "按客户自定义,全局异常------1");
}
public static CommonResult handleException2(BlockException exception){
return new CommonResult(4444, "按客户自定义,全局异常------2");
}
}
- 控制器
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandle.class,
blockHandler = "handleException2"
)
public CommonResult customerBlockHandler(){
return new CommonResult(200, "按客户自定义限流测试OK", new Payment(2020L, "serial003"));
}
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandle.class,
blockHandler = "handleException2"
)
public CommonResult customerBlockHandler(){
return new CommonResult(200, "按客户自定义限流测试OK", new Payment(2020L, "serial003"));
}
- 配置限流
选择按名称限流:
- 访问测试
限流异常走指定的类CustomerBlockHandle的方法handleException2