【Spring Cloud】服务容错中间件Sentinel入门
warning:
这篇文章距离上次修改已过203天,其中的内容可能已经有所变动。
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
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 SentinelExample {
static {
initFlowRules();
}
private static void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("test");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
// Set limit to 20 calls per second.
rule.setCount(20);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
@SentinelResource(value = "test", blockHandler = "handleException")
public void test() {
System.out.println("Test resource invoking...");
}
public void handleException(BlockException ex) {
System.err.println("Test resource handled exception: " + ex.getClass().getCanonicalName());
}
public static void main(String[] args) {
while (true) {
Entry entry = null;
try {
entry = SphU.entry("test");
// Your business logic here.
test();
} catch (BlockException ex) {
// Handle blocked exception.
System.err.println("Blocked!");
} finally {
if (entry != null) {
entry.exit();
}
}
}
}
}
这段代码演示了如何使用Sentinel的注解和API来实现服务的限流。首先,我们初始化了一条流量控制规则,设置了资源名为"test"的QPS阈值为20。接着,我们定义了一个带有Sentinel资源注解的test方法,并指定了异常处理方法handleException。在main方法中,我们持续尝试进入名为"test"的资源,如果被限流,会触发BlockException异常,并调用handleException方法处理。这个例子简单地打印出了异常信息,实际应用中可以根据需要进行更复杂的异常处理。
评论已关闭