SpringCloudAlibaba:@SentinelResource
一、按资源名称添加流控规则
1.新建controller
@RestController
public class SentinelResourceController {
@GetMapping("/resource")
@SentinelResource(value = "resource",blockHandler = "handleException")
public String resource(){
return "SentinelResourceController invoke resource success";
}
public String handleException(BlockException e){
return "SentinelResourceController invoke handleException";
}
}
然后启动项目,在浏览器输入地址,然后在sentinel的控制台就可以看到了
2.新建流控规则
3.测试
刷新频繁会出现
二、自定义异常返回类
1.自定义handler
public class ZrsBlockHandler {
public static String handler1Exception(BlockException exception){
return "ZrsBlockHandler invoke handler【1】Exception";
}
public static String handler2Exception(BlockException exception){
return "ZrsBlockHandler invoke handler【2】Exception";
}
}
2.修改SentinelResourceController
@RestController
public class SentinelResourceController {
@GetMapping("/resource")
@SentinelResource(value = "resource",blockHandler = "handleException")
public String resource(){
return "SentinelResourceController invoke resource success";
}
public String handleException(BlockException e){
return "SentinelResourceController invoke handleException";
}
@GetMapping("/handler1")
@SentinelResource(value = "handler1Exception",blockHandlerClass = ZrsBlockHandler.class,
blockHandler = "handler1Exception")
public String handler1(){
return "SentinelResourceController invoke resource success";
}
@GetMapping("/handler2")
@SentinelResource(value = "handler2Exception",blockHandlerClass = ZrsBlockHandler.class,
blockHandler = "handler2Exception")
public String handler2(){
return "SentinelResourceController invoke resource success";
}
}
3.启动服务
http://localhost:8005/handler1
http://localhost:8005/handler2
4.添加流控规则
5.测试
频繁访问