1、抛出异常的方式定义资源

  1. // 1.5.0 版本开始可以利用 try-with-resources 特性(使用有限制)
  2. // 资源名可使用任意有业务语义的字符串,比如方法名、接口名或其它可唯一标识的字符串。
  3. try (Entry entry = SphU.entry("resourceName")) {
  4. // 被保护的业务逻辑
  5. // do something here...
  6. } catch (BlockException ex) {
  7. // 资源访问阻止,被限流或被降级
  8. // 在此处进行相应的处理操作
  9. }

2、注解方式定义资源

  1. // 原本的业务方法.
  2. @SentinelResource(blockHandler = "blockHandlerForGetUser")
  3. public User getUserById(String id) {
  4. throw new RuntimeException("getUserById command failed");
  5. }
  6. // blockHandler 函数,原方法调用被限流/降级/系统保护的时候调用
  7. public User blockHandlerForGetUser(String id, BlockException ex) {
  8. return new User("admin");
  9. }

结论

使用抛出异常的这种方式,也可以在方法外加上@SentinelResource注解,只要使用@SentinelResource注解就必须设置blockHandler属性