com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager Java Examples

The following examples show how to use com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileDataSourceDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void listenRules() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    String flowRulePath = URLDecoder.decode(classLoader.getResource("FlowRule.json").getFile(), "UTF-8");
    String degradeRulePath = URLDecoder.decode(classLoader.getResource("DegradeRule.json").getFile(), "UTF-8");
    String systemRulePath = URLDecoder.decode(classLoader.getResource("SystemRule.json").getFile(), "UTF-8");

    // Data source for FlowRule
    FileRefreshableDataSource<List<FlowRule>> flowRuleDataSource = new FileRefreshableDataSource<>(
        flowRulePath, flowRuleListParser);
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());

    // Data source for DegradeRule
    FileRefreshableDataSource<List<DegradeRule>> degradeRuleDataSource
        = new FileRefreshableDataSource<>(
        degradeRulePath, degradeRuleListParser);
    DegradeRuleManager.register2Property(degradeRuleDataSource.getProperty());

    // Data source for SystemRule
    FileRefreshableDataSource<List<SystemRule>> systemRuleDataSource
        = new FileRefreshableDataSource<>(
        systemRulePath, systemRuleListParser);
    SystemRuleManager.register2Property(systemRuleDataSource.getProperty());
}
 
Example #2
Source File: SentinelAutoConfigurationTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	FlowRule rule = new FlowRule();
	rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule.setCount(0);
	rule.setResource("GET:" + flowUrl);
	rule.setLimitApp("default");
	rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRuleManager.loadRules(Arrays.asList(rule));

	DegradeRule degradeRule = new DegradeRule();
	degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
	degradeRule.setResource("GET:" + degradeUrl);
	degradeRule.setCount(0);
	degradeRule.setTimeWindow(60);
	DegradeRuleManager.loadRules(Arrays.asList(degradeRule));
}
 
Example #3
Source File: SentinelCircuitBreakerTest.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateDirectlyThenRun() {
	// Create a circuit breaker without any circuit breaking rules.
	CircuitBreaker cb = new SentinelCircuitBreaker(
			"testSentinelCreateDirectlyThenRunA");
	assertThat(cb.run(() -> "Sentinel")).isEqualTo("Sentinel");
	assertThat(DegradeRuleManager.hasConfig("testSentinelCreateDirectlyThenRunA"))
			.isFalse();

	CircuitBreaker cb2 = new SentinelCircuitBreaker(
			"testSentinelCreateDirectlyThenRunB",
			Collections.singletonList(
					new DegradeRule("testSentinelCreateDirectlyThenRunB")
							.setCount(100).setTimeWindow(10)));
	assertThat(cb2.run(() -> "Sentinel")).isEqualTo("Sentinel");
	assertThat(DegradeRuleManager.hasConfig("testSentinelCreateDirectlyThenRunB"))
			.isTrue();
}
 
Example #4
Source File: ExceptionCountDegradeDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void initDegradeRule() {
    List<DegradeRule> rules = new ArrayList<DegradeRule>();
    DegradeRule rule = new DegradeRule();
    rule.setResource(KEY);
    // set limit exception count to 4
    rule.setCount(4);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
    /**
     * When degrading by {@link RuleConstant#DEGRADE_GRADE_EXCEPTION_COUNT}, time window
     * less than 60 seconds will not work as expected. Because the exception count is
     * summed by minute, when a short time window elapsed, the degradation condition
     * may still be satisfied.
     */
    rule.setTimeWindow(10);
    rules.add(rule);
    DegradeRuleManager.loadRules(rules);
}
 
Example #5
Source File: FileDataSourceDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void listenRules() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    String flowRulePath = URLDecoder.decode(classLoader.getResource("FlowRule.json").getFile(), "UTF-8");
    String degradeRulePath = URLDecoder.decode(classLoader.getResource("DegradeRule.json").getFile(), "UTF-8");
    String systemRulePath = URLDecoder.decode(classLoader.getResource("SystemRule.json").getFile(), "UTF-8");

    // Data source for FlowRule
    FileRefreshableDataSource<List<FlowRule>> flowRuleDataSource = new FileRefreshableDataSource<>(
        flowRulePath, flowRuleListParser);
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());

    // Data source for DegradeRule
    FileRefreshableDataSource<List<DegradeRule>> degradeRuleDataSource
        = new FileRefreshableDataSource<>(
        degradeRulePath, degradeRuleListParser);
    DegradeRuleManager.register2Property(degradeRuleDataSource.getProperty());

    // Data source for SystemRule
    FileRefreshableDataSource<List<SystemRule>> systemRuleDataSource
        = new FileRefreshableDataSource<>(
        systemRulePath, systemRuleListParser);
    SystemRuleManager.register2Property(systemRuleDataSource.getProperty());
}
 
Example #6
Source File: ExceptionCountDegradeDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initDegradeRule() {
    List<DegradeRule> rules = new ArrayList<DegradeRule>();
    DegradeRule rule = new DegradeRule();
    rule.setResource(KEY);
    // set limit exception count to 4
    rule.setCount(4);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
    /**
     * When degrading by {@link RuleConstant#DEGRADE_GRADE_EXCEPTION_COUNT}, time window
     * less than 60 seconds will not work as expected. Because the exception count is
     * summed by minute, when a short time window elapsed, the degradation condition
     * may still be satisfied.
     */
    rule.setTimeWindow(10);
    rules.add(rule);
    DegradeRuleManager.loadRules(rules);
}
 
Example #7
Source File: SentinelCircuitBreaker.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private void applyToSentinelRuleManager() {
	if (this.rules == null || this.rules.isEmpty()) {
		return;
	}
	Set<DegradeRule> ruleSet = new HashSet<>(DegradeRuleManager.getRules());
	for (DegradeRule rule : this.rules) {
		if (rule == null) {
			continue;
		}
		rule.setResource(resourceName);
		ruleSet.add(rule);
	}
	DegradeRuleManager.loadRules(new ArrayList<>(ruleSet));
}
 
Example #8
Source File: FetchActiveRuleCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String type = request.getParam("type");
    if ("flow".equalsIgnoreCase(type)) {
        return CommandResponse.ofSuccess(JSON.toJSONString(FlowRuleManager.getRules()));
    } else if ("degrade".equalsIgnoreCase(type)) {
        return CommandResponse.ofSuccess(JSON.toJSONString(DegradeRuleManager.getRules()));
    } else if ("authority".equalsIgnoreCase(type)) {
        return CommandResponse.ofSuccess(JSON.toJSONString(AuthorityRuleManager.getRules()));
    } else if ("system".equalsIgnoreCase(type)) {
        return CommandResponse.ofSuccess(JSON.toJSONString(SystemRuleManager.getRules()));
    } else {
        return CommandResponse.ofFailure(new IllegalArgumentException("invalid type"));
    }
}
 
Example #9
Source File: SentinelEndpoint.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@ReadOperation
public Map<String, Object> invoke() {
	final Map<String, Object> result = new HashMap<>();
	if (sentinelProperties.isEnabled()) {

		result.put("appName", AppNameUtil.getAppName());
		result.put("logDir", LogBase.getLogBaseDir());
		result.put("logUsePid", LogBase.isLogNameUsePid());
		result.put("blockPage", SentinelConfig.getConfig(BLOCK_PAGE_URL_CONF_KEY));
		result.put("metricsFileSize", SentinelConfig.singleMetricFileSize());
		result.put("metricsFileCharset", SentinelConfig.charset());
		result.put("totalMetricsFileCount", SentinelConfig.totalMetricFileCount());
		result.put("consoleServer", TransportConfig.getConsoleServerList());
		result.put("clientIp", TransportConfig.getHeartbeatClientIp());
		result.put("heartbeatIntervalMs", TransportConfig.getHeartbeatIntervalMs());
		result.put("clientPort", TransportConfig.getPort());
		result.put("coldFactor", sentinelProperties.getFlow().getColdFactor());
		result.put("filter", sentinelProperties.getFilter());
		result.put("datasource", sentinelProperties.getDatasource());

		final Map<String, Object> rules = new HashMap<>();
		result.put("rules", rules);
		rules.put("flowRules", FlowRuleManager.getRules());
		rules.put("degradeRules", DegradeRuleManager.getRules());
		rules.put("systemRules", SystemRuleManager.getRules());
		rules.put("authorityRule", AuthorityRuleManager.getRules());
		rules.put("paramFlowRule", ParamFlowRuleManager.getRules());
	}
	return result;
}
 
Example #10
Source File: SentinelCircuitBreakerTest.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithNullRule() {
	String id = "testCreateCbWithNullRule";
	CircuitBreaker cb = new SentinelCircuitBreaker(id,
			Collections.singletonList(null));
	assertThat(cb.run(() -> "Sentinel")).isEqualTo("Sentinel");
	assertThat(DegradeRuleManager.hasConfig(id)).isFalse();
}
 
Example #11
Source File: ReactiveSentinelCircuitBreakerTest.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithNullRule() {
	String id = "testCreateReactiveCbWithNullRule";
	ReactiveSentinelCircuitBreaker cb = new ReactiveSentinelCircuitBreaker(id,
			Collections.singletonList(null));
	assertThat(Mono.just("foobar").transform(it -> cb.run(it)).block())
			.isEqualTo("foobar");
	assertThat(DegradeRuleManager.hasConfig(id)).isFalse();
}
 
Example #12
Source File: ReactiveSentinelCircuitBreaker.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private void applyToSentinelRuleManager() {
	if (this.rules == null || this.rules.isEmpty()) {
		return;
	}
	Set<DegradeRule> ruleSet = new HashSet<>(DegradeRuleManager.getRules());
	for (DegradeRule rule : this.rules) {
		if (rule == null) {
			continue;
		}
		rule.setResource(resourceName);
		ruleSet.add(rule);
	}
	DegradeRuleManager.loadRules(new ArrayList<>(ruleSet));
}
 
Example #13
Source File: FetchActiveRuleCommandHandler.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String type = request.getParam("type");
    if ("flow".equalsIgnoreCase(type)) {
        return CommandResponse.ofSuccess(JSON.toJSONString(FlowRuleManager.getRules()));
    } else if ("degrade".equalsIgnoreCase(type)) {
        return CommandResponse.ofSuccess(JSON.toJSONString(DegradeRuleManager.getRules()));
    } else if ("authority".equalsIgnoreCase(type)) {
        return CommandResponse.ofSuccess(JSON.toJSONString(AuthorityRuleManager.getRules()));
    } else if ("system".equalsIgnoreCase(type)) {
        return CommandResponse.ofSuccess(JSON.toJSONString(SystemRuleManager.getRules()));
    } else {
        return CommandResponse.ofFailure(new IllegalArgumentException("invalid type"));
    }
}
 
Example #14
Source File: AbstractDataSourceProperties.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public void postRegister(AbstractDataSource dataSource) {
	switch (this.getRuleType()) {
	case FLOW:
		FlowRuleManager.register2Property(dataSource.getProperty());
		break;
	case DEGRADE:
		DegradeRuleManager.register2Property(dataSource.getProperty());
		break;
	case PARAM_FLOW:
		ParamFlowRuleManager.register2Property(dataSource.getProperty());
		break;
	case SYSTEM:
		SystemRuleManager.register2Property(dataSource.getProperty());
		break;
	case AUTHORITY:
		AuthorityRuleManager.register2Property(dataSource.getProperty());
		break;
	case GW_FLOW:
		GatewayRuleManager.register2Property(dataSource.getProperty());
		break;
	case GW_API_GROUP:
		GatewayApiDefinitionManager.register2Property(dataSource.getProperty());
		break;
	default:
		break;
	}
}
 
Example #15
Source File: BaseTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void cleanUpCstContext() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    ClusterBuilderSlot.getClusterNodeMap().clear();
    CtSph.resetChainMap();
    Method method = ContextUtil.class.getDeclaredMethod("resetContextMap");
    method.setAccessible(true);
    method.invoke(null, null);
    ContextUtil.exit();
    FlowRuleManager.loadRules(new ArrayList<>());
    DegradeRuleManager.loadRules(new ArrayList<>());
}
 
Example #16
Source File: SentinelDubboConsumerFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void initDegradeRule(String resource) {
    DegradeRule degradeRule = new DegradeRule(resource)
            .setCount(0.5)
            .setGrade(DEGRADE_GRADE_EXCEPTION_RATIO);
    List<DegradeRule> degradeRules = new ArrayList<>();
    degradeRules.add(degradeRule);
    degradeRule.setTimeWindow(1);
    DegradeRuleManager.loadRules(degradeRules);
}
 
Example #17
Source File: AppLifecycleBean.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
void onStart(@Observes StartupEvent ev) {
    LOGGER.info("The application is starting...");
    FlowRule rule = new FlowRule()
            .setCount(1)
            .setGrade(RuleConstant.FLOW_GRADE_QPS)
            .setResource("GET:/hello/txt")
            .setLimitApp("default")
            .as(FlowRule.class);
    FlowRuleManager.loadRules(Arrays.asList(rule));

    SystemRule systemRule = new SystemRule();
    systemRule.setLimitApp("default");
    systemRule.setAvgRt(3000);
    SystemRuleManager.loadRules(Arrays.asList(systemRule));

    DegradeRule degradeRule1 = new DegradeRule("greeting1")
            .setCount(1)
            .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT)
            .setTimeWindow(10)
            .setMinRequestAmount(1);

    DegradeRule degradeRule2 = new DegradeRule("greeting2")
            .setCount(1)
            .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT)
            .setTimeWindow(10)
            .setMinRequestAmount(1);
    DegradeRuleManager.loadRules(Arrays.asList(degradeRule1, degradeRule2));
}
 
Example #18
Source File: FooConsumerExceptionDegradeBootstrap.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void initExceptionFallback(int timewindow) {
    DegradeRule degradeRule = new DegradeRule(INTERFACE_RES_KEY)
            .setCount(0.5)
            .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO)
            .setTimeWindow(timewindow)
            .setMinRequestAmount(1);
    DegradeRuleManager.loadRules(Collections.singletonList(degradeRule));

}
 
Example #19
Source File: RtDegradeDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void initDegradeRule() {
    List<DegradeRule> rules = new ArrayList<DegradeRule>();
    DegradeRule rule = new DegradeRule();
    rule.setResource(KEY);
    // set threshold rt, 10 ms
    rule.setCount(10);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
    rule.setTimeWindow(10);
    rules.add(rule);
    DegradeRuleManager.loadRules(rules);
}
 
Example #20
Source File: ExceptionRatioDegradeDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void initDegradeRule() {
    List<DegradeRule> rules = new ArrayList<DegradeRule>();
    DegradeRule rule = new DegradeRule();
    rule.setResource(KEY);
    // set limit exception ratio to 0.1
    rule.setCount(0.1);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
    rule.setTimeWindow(10);
    rule.setMinRequestAmount(20);
    rules.add(rule);
    DegradeRuleManager.loadRules(rules);
}
 
Example #21
Source File: ExceptionRatioDegradeDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private static void initDegradeRule() {
    List<DegradeRule> rules = new ArrayList<DegradeRule>();
    DegradeRule rule = new DegradeRule();
    rule.setResource(KEY);
    // set limit exception ratio to 0.1
    rule.setCount(0.1);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
    rule.setTimeWindow(10);
    rule.setMinRequestAmount(20);
    rules.add(rule);
    DegradeRuleManager.loadRules(rules);
}
 
Example #22
Source File: RtDegradeDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private static void initDegradeRule() {
    List<DegradeRule> rules = new ArrayList<DegradeRule>();
    DegradeRule rule = new DegradeRule();
    rule.setResource(KEY);
    // set threshold rt, 10 ms
    rule.setCount(10);
    rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
    rule.setTimeWindow(10);
    rules.add(rule);
    DegradeRuleManager.loadRules(rules);
}
 
Example #23
Source File: SentinelCircuitBreakerIntegrationTest.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
	DegradeRuleManager.loadRules(new ArrayList<>());
}
 
Example #24
Source File: SentinelCircuitBreakerIntegrationTest.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Before
public void tearDown() {
	DegradeRuleManager.loadRules(new ArrayList<>());
}
 
Example #25
Source File: SentinelCircuitBreakerTest.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
	// Clear the rules.
	DegradeRuleManager.loadRules(new ArrayList<>());
}