1、抛出异常的方式定义资源
// 1.5.0 版本开始可以利用 try-with-resources 特性(使用有限制)// 资源名可使用任意有业务语义的字符串,比如方法名、接口名或其它可唯一标识的字符串。try (Entry entry = SphU.entry("resourceName")) {// 被保护的业务逻辑// do something here...} catch (BlockException ex) {// 资源访问阻止,被限流或被降级// 在此处进行相应的处理操作}
2、注解方式定义资源
// 原本的业务方法.@SentinelResource(blockHandler = "blockHandlerForGetUser")public User getUserById(String id) {throw new RuntimeException("getUserById command failed");}// blockHandler 函数,原方法调用被限流/降级/系统保护的时候调用public User blockHandlerForGetUser(String id, BlockException ex) {return new User("admin");}
结论
使用抛出异常的这种方式,也可以在方法外加上@SentinelResource注解,只要使用@SentinelResource注解就必须设置blockHandler属性
