跳到主要内容

(七) API、注解、整合Feign

Sentinel API

这里介绍三个重要的API。

  • ContextUtil
  • Tracer
  • SphU
    @GetMapping("/test-sentinel-api")
public String testSentinelApi(@RequestParam(required = false) String a) {



//定义一个sentinel受保护的资源,名称是test-sentinel-api
String resourceName = "test-sentinel-api";
//
ContextUtil.enter(resourceName, "test-wfw");
Entry entry = null;
try {



entry = SphU.entry(resourceName);
//被保护的逻辑
if (StringUtils.isEmpty(a)) {



throw new IllegalArgumentException("a is not null");
}
return a;
} catch (BlockException be) {



//如果受保护的资源被限流或者降级了 就会抛BlockException
log.warn("限流或者降级了", be);
return "限流或者降级了";
} catch (IllegalArgumentException ie) {



//统计 IllegalArgumentException 发生的次数、占比。。。
Tracer.trace(ie);
return "a is not null";
} finally {



if(entry != null) {



//退出entry
entry.exit();
}
ContextUtil.exit();
}

}