Sentinel
提供了一系列的注解来简化流量控制、降级和熔断等操作的配置和实现。这些注解使得开发者可以在代码层面更加方便地集成 Sentinel 的功能,而无需在每个地方都显式地调用 Sentinel 的 API。以下是 Sentinel 支持的主要注解及其用途:
主要注解
-
@SentinelResource
- 作用:标记一个方法或类为 Sentinel 资源,可以对其进行流量控制、降级和熔断等操作。
- 属性:
value
:资源名称,用于标识该资源。blockHandler
:当请求被限流或降级时,将调用该方法来处理异常。blockHandlerClass
:指定 blockHandler 方法所在的类。fallback
:当目标方法抛出异常时,可以调用此方法作为备选方法。fallbackClass
:指定 fallback 方法所在的类。exceptionsToIgnore
:指定哪些异常可以忽略,不会触发 fallback 或 blockHandler 方法。
示例代码:
@SentinelResource(value = "hello", blockHandler = "handleException") public String hello(@RequestParam("name") String name) { return "Hello, " + name; } public String handleException(BlockException ex) { return "Request blocked."; }
-
@SentinelInit
- 作用:标记一个方法或类为初始化方法,在 Sentinel 初始化时执行。
- 属性:
entryType
:指定入口类型,例如ENTRY_TYPE_IN
表示入口类型为 IN。
- 通常用于在启动时加载一些规则或初始化一些资源。
-
@SentinelTransaction
- 作用:标记一个方法或类为事务性资源,可以配合
@SentinelTransactionEnd
使用。 - 属性:
value
:资源名称。
- 用于事务控制场景。
- 作用:标记一个方法或类为事务性资源,可以配合
-
@SentinelTransactionEnd
- 作用:标记事务结束的位置。
- 通常与
@SentinelTransaction
配合使用,用于结束一个事务。
使用示例
假设我们有一个简单的服务,我们需要对其进行流量控制,并且当请求被限流时,返回一个友好的提示信息。
定义服务接口
public interface HelloService {
String hello(String name);
}
实现服务接口
@Service
public class HelloServiceImpl implements HelloService {
@Override
@SentinelResource(value = "hello", blockHandler = "handleException")
public String hello(String name) {
// 业务逻辑
return "Hello, " + name;
}
public String handleException(BlockException ex) {
// 当请求被限流时,返回的信息
return "Request blocked.";
}
}
配置限流规则
你可以在 Sentinel 控制台中手动配置限流规则,或者通过代码动态加载规则:
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import java.util.ArrayList;
import java.util.List;
public class FlowRuleConfig {
public static void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("hello");
rule.setCount(10); // 每秒允许通过的最大请求数量
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流模式:QPS
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
}
在 Spring Boot 中自动配置 Sentinel
如果你使用的是 Spring Boot,可以使用 Sentinel 的 Starter 包来自动配置 Sentinel,并注册上面定义的规则:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public FlowRuleConfig flowRuleConfig() {
return new FlowRuleConfig();
}
}
通过以上步骤,你可以使用 Sentinel 的注解来轻松地为你的服务添加流量控制、降级和熔断的功能。这些注解简化了 Sentinel 的集成过程,并且使得代码更加清晰易懂。