com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager Java Examples

The following examples show how to use com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager. 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: ApolloDataSourceDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void loadRules() {
    // Set up basic information, only for demo purpose. You may adjust them based on your actual environment.
    // For more information, please refer https://github.com/ctripcorp/apollo
    String appId = "sentinel-demo";
    String apolloMetaServerAddress = "http://localhost:8080";
    System.setProperty("app.id", appId);
    System.setProperty("apollo.meta", apolloMetaServerAddress);

    String namespaceName = "application";
    String flowRuleKey = "flowRules";
    // It's better to provide a meaningful default value.
    String defaultFlowRules = "[]";

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ApolloDataSource<>(namespaceName,
        flowRuleKey, defaultFlowRules, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
    }));
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
 
Example #2
Source File: ReactorSphUTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testReactorEntryNormalWhenFlowControlTriggered() {
    String resourceName = createResourceName("testReactorEntryNormalWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(ReactorSphU.entryWith(resourceName, Mono.just(60))
        .subscribeOn(Schedulers.elastic())
        .map(e -> e * 3))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #3
Source File: PullConsumerDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initFlowControlRule() {
    FlowRule rule = new FlowRule();
    rule.setResource(KEY);
    // Indicates the interval between two adjacent requests is 200 ms.
    rule.setCount(5);
    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setLimitApp("default");

    // Enable rate limiting (uniform). This can ensure fixed intervals between two adjacent calls.
    // In this example, intervals between two incoming calls (message consumption) will be 200 ms constantly.
    rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
    // If more requests are coming, they'll be put into the waiting queue.
    // The queue has a queueing timeout. Requests that may exceed the timeout will be immediately blocked.
    // In this example, the max timeout is 5s.
    rule.setMaxQueueingTimeMs(5 * 1000);
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #4
Source File: ApolloDataSourceDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void loadRules() {
    // Set up basic information, only for demo purpose. You may adjust them based on your actual environment.
    // For more information, please refer https://github.com/ctripcorp/apollo
    String appId = "sentinel-demo";
    String apolloMetaServerAddress = "http://localhost:8080";
    System.setProperty("app.id", appId);
    System.setProperty("apollo.meta", apolloMetaServerAddress);

    String namespaceName = "application";
    String flowRuleKey = "flowRules";
    // It's better to provide a meaningful default value.
    String defaultFlowRules = "[]";

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ApolloDataSource<>(namespaceName,
        flowRuleKey, defaultFlowRules, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
    }));
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
 
Example #5
Source File: MonoSentinelOperatorIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitSingleValueWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitSingleValueWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Mono.just(1)
        .map(e -> e * 2)
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #6
Source File: SentinelAnnotationInterceptorIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultFallbackWithSingleParam() {
    assertThat(fooService.anotherFoo(1)).isEqualTo("Hello for 1");
    String resourceName = "apiAnotherFooWithDefaultFallback";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();

    // Default fallback should take effect.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.exceptionQps()).isPositive();
    assertThat(cn.blockQps()).isZero();

    FlowRuleManager.loadRules(Collections.singletonList(
            new FlowRule(resourceName).setCount(0)
    ));
    // Default fallback should also take effect for BlockException.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.blockQps()).isPositive();
}
 
Example #7
Source File: FileDataSourceInit.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws Exception {
    // A fake path.
    String flowRuleDir = System.getProperty("user.home") + File.separator + "sentinel" + File.separator + "rules";
    String flowRuleFile = "flowRule.json";
    String flowRulePath = flowRuleDir + File.separator + flowRuleFile;

    ReadableDataSource<String, List<FlowRule>> ds = new FileRefreshableDataSource<>(
        flowRulePath, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {})
    );
    // Register to flow rule manager.
    FlowRuleManager.register2Property(ds.getProperty());

    WritableDataSource<List<FlowRule>> wds = new FileWritableDataSource<>(flowRulePath, this::encodeJson);
    // Register to writable data source registry so that rules can be updated to file
    // when there are rules pushed from the Sentinel Dashboard.
    WritableDataSourceRegistry.registerFlowDataSource(wds);
}
 
Example #8
Source File: EtcdDataSourceDemo.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        String rule_key = "sentinel_demo_rule_key";
        String yourUserName = "root";
        String yourPassWord = "12345";
        String endPoints = "http://127.0.0.1:2379";
        SentinelConfig.setConfig(EtcdConfig.END_POINTS, endPoints);
        SentinelConfig.setConfig(EtcdConfig.USER, yourUserName);
        SentinelConfig.setConfig(EtcdConfig.PASSWORD, yourPassWord);
        SentinelConfig.setConfig(EtcdConfig.CHARSET, "utf-8");
        SentinelConfig.setConfig(EtcdConfig.AUTH_ENABLE, "true");

        ReadableDataSource<String, List<FlowRule>> flowRuleEtcdDataSource = new EtcdDataSource<>(rule_key, (rule) -> JSON.parseArray(rule, FlowRule.class));
        FlowRuleManager.register2Property(flowRuleEtcdDataSource.getProperty());
        List<FlowRule> rules = FlowRuleManager.getRules();
        System.out.println(rules);
    }
 
Example #9
Source File: SentinelAnnotationQuarkusAdapterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testBlockHandlerNotFound() {
    assertThat(fooService.baz("Sentinel")).isEqualTo("cheers, Sentinel");
    String resourceName = "apiBaz";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();

    FlowRuleManager.loadRules(Collections.singletonList(
            new FlowRule(resourceName).setCount(0)
    ));

    Assertions.assertThrows(ArcUndeclaredThrowableException.class, () -> {
        fooService.baz("Sentinel");
    });
}
 
Example #10
Source File: SentinelAnnotationIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultFallbackWithSingleParam() {
    assertThat(fooService.anotherFoo(1)).isEqualTo("Hello for 1");
    String resourceName = "apiAnotherFooWithDefaultFallback";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();

    // Default fallback should take effect.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.exceptionQps()).isPositive();
    assertThat(cn.blockQps()).isZero();

    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    // Default fallback should also take effect for BlockException.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.blockQps()).isPositive();
}
 
Example #11
Source File: FluxSentinelOperatorTestIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitMultipleValuesWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitMultipleValuesWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Flux.just(1, 3, 5)
        .map(e -> e * 2)
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #12
Source File: PaceFlowDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initPaceFlowRule() {
    List<FlowRule> rules = new ArrayList<FlowRule>();
    FlowRule rule1 = new FlowRule();
    rule1.setResource(KEY);
    rule1.setCount(count);
    rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule1.setLimitApp("default");
    /*
     * CONTROL_BEHAVIOR_RATE_LIMITER means requests more than threshold will be queueing in the queue,
     * until the queueing time is more than {@link FlowRule#maxQueueingTimeMs}, the requests will be rejected.
     */
    rule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
    rule1.setMaxQueueingTimeMs(20 * 1000);

    rules.add(rule1);
    FlowRuleManager.loadRules(rules);
}
 
Example #13
Source File: SentinelAnnotationIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultFallbackWithSingleParam() {
    assertThat(fooService.anotherFoo(1)).isEqualTo("Hello for 1");
    String resourceName = "apiAnotherFooWithDefaultFallback";
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertThat(cn).isNotNull();
    assertThat(cn.passQps()).isPositive();

    // Default fallback should take effect.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.exceptionQps()).isPositive();
    assertThat(cn.blockQps()).isZero();

    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    // Default fallback should also take effect for BlockException.
    assertThat(fooService.anotherFoo(5758)).isEqualTo(FooUtil.FALLBACK_DEFAULT_RESULT);
    assertThat(cn.blockQps()).isPositive();
}
 
Example #14
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 #15
Source File: MonoSentinelOperatorIntegrationTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitExceptionWhenFlowControlTriggered() {
    String resourceName = createResourceName("testEmitExceptionWhenFlowControlTriggered");
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0)
    ));
    StepVerifier.create(Mono.error(new IllegalStateException("some"))
        .transform(new SentinelReactorTransformer<>(resourceName)))
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
Example #16
Source File: CommonFilterMethodTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void testCommonBlockAndRedirectBlockPage(String url, ClusterNode cnGet, ClusterNode cnPost) throws Exception {
    configureRulesFor(GET + ":" + url, 0);
    // The request will be blocked and response is default block message.
    this.mvc.perform(get(url).accept(MediaType.TEXT_PLAIN))
            .andExpect(status().isOk())
            .andExpect(content().string(FilterUtil.DEFAULT_BLOCK_MSG));
    assertEquals(1, cnGet.blockQps(), 0.01);

    // Test for post pass
    this.mvc.perform(post(url))
            .andExpect(status().isOk())
            .andExpect(content().string(HELLO_POST_STR));

    assertEquals(2, cnPost.passQps(), 0.01);


    FlowRuleManager.loadRules(null);
    WebServletConfig.setBlockPage("");
}
 
Example #17
Source File: HttpServerHandlerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testFetchActiveRuleCommandSomeFlowRules() {
    List<FlowRule> rules = new ArrayList<FlowRule>();
    FlowRule rule1 = new FlowRule();
    rule1.setResource("key");
    rule1.setCount(20);
    rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule1.setLimitApp("default");
    rules.add(rule1);
    FlowRuleManager.loadRules(rules);

    String httpRequestStr = "GET /getRules?type=flow HTTP/1.1" + CRLF
                          + "Host: localhost:8719" + CRLF
                          + CRLF;

    // body json
    /*
    String expectedBody = "[{\"clusterMode\":false,\"controlBehavior\":0,\"count\":20.0"
            + ",\"grade\":1,\"limitApp\":\"default\",\"maxQueueingTimeMs\":500"
            + ",\"resource\":\"key\",\"strategy\":0,\"warmUpPeriodSec\":10}]";
    */
    String expectedBody = JSON.toJSONString(rules);

    processSuccess(httpRequestStr, expectedBody);
}
 
Example #18
Source File: SentinelStart.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void initFlowRules() {
	List<FlowRule> rules = new ArrayList<>();
	FlowRule rule = new FlowRule();
	rule.setResource("HelloWorld");
	rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
	// Set limit QPS to 20.
	rule.setCount(20);
	rules.add(rule);
	FlowRuleManager.loadRules(rules);
}
 
Example #19
Source File: SentinelFeignTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	FlowRule rule1 = new FlowRule();
	rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule1.setCount(0);
	rule1.setResource("GET:http://test-service/echo/{str}");
	rule1.setLimitApp("default");
	rule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule1.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRule rule2 = new FlowRule();
	rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule2.setCount(0);
	rule2.setResource("GET:http://foo-service/echo/{str}");
	rule2.setLimitApp("default");
	rule2.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule2.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRule rule3 = new FlowRule();
	rule3.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule3.setCount(0);
	rule3.setResource("GET:http://bar-service/bar");
	rule3.setLimitApp("default");
	rule3.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule3.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRule rule4 = new FlowRule();
	rule4.setGrade(RuleConstant.FLOW_GRADE_QPS);
	rule4.setCount(0);
	rule4.setResource("GET:http://baz-service/baz");
	rule4.setLimitApp("default");
	rule4.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	rule4.setStrategy(RuleConstant.STRATEGY_DIRECT);
	FlowRuleManager.loadRules(Arrays.asList(rule1, rule2, rule3, rule4));
}
 
Example #20
Source File: SentinelSpringMvcIntegrationTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
            .setCount(count)
            .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #21
Source File: ClusterFlowClientController.java    From sentinel-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * 注册动态规则Property
 * 当client与Server连接中断,退化为本地限流时需要用到的该规则
 */
private void registerClusterFlowRuleProperty(){
    // 使用 Nacos 数据源作为配置中心,需要在 REMOTE_ADDRESS 上启动一个 Nacos 的服务
    ReadableDataSource<String, List<FlowRule>> ds = new NacosDataSource<>(REMOTE_ADDRESS, GROUP_ID, APP_NAME+FLOW_POSTFIX,
            source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
    // 为集群客户端注册动态规则源
    FlowRuleManager.register2Property(ds.getProperty());
}
 
Example #22
Source File: SentinelModeRedisDataSourceTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectToSentinelAndPubMsgSuccess() {
    int maxQueueingTimeMs = new Random().nextInt();
    String flowRulesJson =
        "[{\"resource\":\"test\", \"limitApp\":\"default\", \"grade\":1, \"count\":\"0.0\", \"strategy\":0, "
            + "\"refResource\":null, "
            +
            "\"controlBehavior\":0, \"warmUpPeriodSec\":10, \"maxQueueingTimeMs\":" + maxQueueingTimeMs
            + ", \"controller\":null}]";
    RedisCommands<String, String> subCommands = client.connect().sync();
    subCommands.multi();
    subCommands.set(ruleKey, flowRulesJson);
    subCommands.publish(channel, flowRulesJson);
    subCommands.exec();

    await().timeout(2, TimeUnit.SECONDS)
        .until(new Callable<List<FlowRule>>() {
            @Override
            public List<FlowRule> call() throws Exception {
                return FlowRuleManager.getRules();
            }
        }, Matchers.hasSize(1));

    List<FlowRule> rules = FlowRuleManager.getRules();
    Assert.assertEquals(rules.get(0).getMaxQueueingTimeMs(), maxQueueingTimeMs);
    String value = subCommands.get(ruleKey);
    List<FlowRule> flowRulesValuesInRedis = buildFlowConfigParser().convert(value);
    Assert.assertEquals(flowRulesValuesInRedis.size(), 1);
    Assert.assertEquals(flowRulesValuesInRedis.get(0).getMaxQueueingTimeMs(), maxQueueingTimeMs);
}
 
Example #23
Source File: SpringCouldDataSourceTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@GetMapping("/get")
@ResponseBody
public List<FlowRule> get() {
    SpringCloudConfigDataSource dataSource = new SpringCloudConfigDataSource("flow_rule", converter);
    FlowRuleManager.register2Property(dataSource.getProperty());
    return FlowRuleManager.getRules();
}
 
Example #24
Source File: JarFileDataSourceDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void listenRules() throws Exception {
    // Modify the path with your real path.
    String jarPath = System.getProperty("user.dir") + "/sentinel-demo/sentinel-demo-dynamic-file-rule/target/"
        + "sentinel-demo-dynamic-file-rule.jar";
    // eg: if flowRuleInJarName full path is 'sentinel-demo-dynamic-file-rule.jar!/classes/FlowRule.json',
    // your flowRuleInJarName is 'classes/FlowRule.json'
    String flowRuleInJarPath = "FlowRule.json";

    FileInJarReadableDataSource<List<FlowRule>> flowRuleDataSource = new FileInJarReadableDataSource<>(
            jarPath,flowRuleInJarPath, flowRuleListParser);
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
 
Example #25
Source File: SentinelModeRedisDataSourceTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Before
public void initData() {
    Converter<String, List<FlowRule>> flowConfigParser = buildFlowConfigParser();
    RedisConnectionConfig config = RedisConnectionConfig.builder()
        .withRedisSentinel(host, redisSentinelPort)
        .withRedisSentinel(host, redisSentinelPort)
        .withSentinelMasterId(redisSentinelMasterId).build();
    initRedisRuleData();
    ReadableDataSource<String, List<FlowRule>> redisDataSource = new RedisDataSource<>(config,
        ruleKey, channel, flowConfigParser);
    FlowRuleManager.register2Property(redisDataSource.getProperty());
}
 
Example #26
Source File: DataSourcePropertiesTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostRegister() throws Exception {
	FileDataSourceProperties fileDataSourceProperties = new FileDataSourceProperties();

	fileDataSourceProperties.setFile("classpath: flowrule.json");
	fileDataSourceProperties.setRuleType(RuleType.FLOW);

	FileRefreshableDataSource fileRefreshableDataSource = new FileRefreshableDataSource(
			ResourceUtils
					.getFile(StringUtils
							.trimAllWhitespace(fileDataSourceProperties.getFile()))
					.getAbsolutePath(),
			new Converter<String, List<FlowRule>>() {
				ObjectMapper objectMapper = new ObjectMapper();

				@Override
				public List<FlowRule> convert(String source) {
					try {
						return objectMapper.readValue(source,
								new TypeReference<List<FlowRule>>() {
								});
					}
					catch (IOException e) {
						// ignore
					}
					return null;
				}
			});
	fileDataSourceProperties.postRegister(fileRefreshableDataSource);
	assertThat(FlowRuleManager.getRules())
			.isEqualTo(fileRefreshableDataSource.loadConfig());
}
 
Example #27
Source File: SentinelWebFluxIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
        .setCount(count)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #28
Source File: ZookeeperDataSourceTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testZooKeeperDataSource() throws Exception {
    TestingServer server = new TestingServer(21812);
    server.start();

    final String remoteAddress = server.getConnectString();
    final String path = "/sentinel-zk-ds-demo/flow-HK";

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<List<FlowRule>>(remoteAddress, path,
            new Converter<String, List<FlowRule>>() {
                @Override
                public List<FlowRule> convert(String source) {
                    return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                    });
                }
            });
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());

    CuratorFramework zkClient = CuratorFrameworkFactory.newClient(remoteAddress,
            new ExponentialBackoffRetry(3, 1000));
    zkClient.start();
    Stat stat = zkClient.checkExists().forPath(path);
    if (stat == null) {
        zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null);
    }

    final String resourceName = "HK";
    publishThenTestFor(zkClient, path, resourceName, 10);
    publishThenTestFor(zkClient, path, resourceName, 15);

    zkClient.close();
    server.stop();
}
 
Example #29
Source File: SentinelGrpcClientInterceptorTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void configureFlowRule(int count) {
    FlowRule rule = new FlowRule()
        .setCount(count)
        .setGrade(RuleConstant.FLOW_GRADE_QPS)
        .setResource(resourceName)
        .setLimitApp("default")
        .as(FlowRule.class);
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example #30
Source File: SentinelGrpcServerInterceptorTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void configureFlowRule(int count) {
    FlowRule rule = new FlowRule()
        .setCount(count)
        .setGrade(RuleConstant.FLOW_GRADE_QPS)
        .setResource(resourceName)
        .setLimitApp("default")
        .as(FlowRule.class);
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}