Sentinel API
Sentinel 提供了一系列的 Java API,开发者可以直接在代码中定义资源并设置流量控制、熔断降级等规则。例如:
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
// 定义资源
String resource = "myResource";
// 创建一个资源入口
try (Entry entry = SphU.entry(resource)) {
// 业务逻辑代码...
} catch (BlockException ex) {
// 处理被流控的情况(如记录日志、返回错误信息等)
}
// 动态添加流控规则
FlowRule rule = new FlowRule(resource)
.setCount(10) // 设置限流阈值为每秒10个请求
.setGrade(RuleConstant.FLOW_GRADE_QPS); // 设置限流模式为QPS模式
FlowRuleManager.loadRules(Arrays.asList(rule));
Sentinel 注解
Sentinel 还提供了 @SentinelResource
注解来简化资源定义和异常处理:
import com.alibaba.csp.sentinel.annotation.SentinelResource;
@Service
public class MyService {
@SentinelResource(value = "myMethod", blockHandler = "handleException")
public String myMethod(String param) {
// 业务逻辑...
return "Hello, Sentinel!";
}
// 异常处理方法
public String handleException(BlockException ex) {
// 当 myMethod 被限流或降级时,将调用此方法
return "Oops, method is blocked by Sentinel";
}
}
Sentinel 整合 Feign
Feign 是一个声明式的 HTTP 客户端,Spring Cloud Alibaba Sentinel 提供了对 Feign 的支持,可以在客户端进行服务间调用时实现流量控制和熔断降级。
要整合 Sentinel 和 Feign,你需要做以下配置:
-
添加依赖:
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
-
配置启用 Sentinel 对 Feign 的支持:
@Configuration @EnableFeignClients public class FeignConfig { @Bean public SentinelFeignBuilder sentinelFeignBuilder() { return new SentinelFeignBuilder(); } }
-
在使用 FeignClient 的接口上使用
@SentinelResource
注解定义资源:@FeignClient(name = "microservice-provider", configuration = FeignConfig.class) public interface ProviderService { @GetMapping("/provider/api") @SentinelResource("providerApi") String providerApi(); }
通过以上步骤,Sentinel 将对 Feign 客户端发起的服务间调用提供相应的保护策略。