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

The following examples show how to use com.alibaba.csp.sentinel.slots.block.flow.FlowRule. 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: ModifyClusterFlowRulesCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String namespace = request.getParam("namespace");
    if (StringUtil.isEmpty(namespace)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty namespace"));
    }
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "UTF-8");
        RecordLog.info("[ModifyClusterFlowRulesCommandHandler] Receiving cluster flow rules for namespace <{}>: {}", namespace, data);

        List<FlowRule> flowRules = JSONArray.parseArray(data, FlowRule.class);
        ClusterFlowRuleManager.loadRules(namespace, flowRules);

        return CommandResponse.ofSuccess(SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterFlowRulesCommandHandler] Decode cluster flow rules error", e);
        return CommandResponse.ofFailure(e, "decode cluster flow rules error");
    }
}
 
Example #2
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 #3
Source File: FlowRuleEntity.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public static FlowRuleEntity fromFlowRule(String app, String ip, Integer port, FlowRule rule) {
    FlowRuleEntity entity = new FlowRuleEntity();
    entity.setApp(app);
    entity.setIp(ip);
    entity.setPort(port);
    entity.setLimitApp(rule.getLimitApp());
    entity.setResource(rule.getResource());
    entity.setGrade(rule.getGrade());
    entity.setCount(rule.getCount());
    entity.setStrategy(rule.getStrategy());
    entity.setRefResource(rule.getRefResource());
    entity.setControlBehavior(rule.getControlBehavior());
    entity.setWarmUpPeriodSec(rule.getWarmUpPeriodSec());
    entity.setMaxQueueingTimeMs(rule.getMaxQueueingTimeMs());
    entity.setClusterMode(rule.isClusterMode());
    entity.setClusterConfig(rule.getClusterConfig());
    return entity;
}
 
Example #4
Source File: HttpServerHandlerTest.java    From Sentinel 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 #5
Source File: AsyncEntryDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static void initFlowRule() {
    // Rule 1 won't take effect as the limitApp doesn't match.
    FlowRule rule1 = new FlowRule()
        .setResource("test-another-sync-in-async")
        .setLimitApp("originB")
        .as(FlowRule.class)
        .setCount(4)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    // Rule 2 will take effect.
    FlowRule rule2 = new FlowRule()
        .setResource("test-another-async")
        .setLimitApp("default")
        .as(FlowRule.class)
        .setCount(5)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    List<FlowRule> ruleList = Arrays.asList(rule1, rule2);
    FlowRuleManager.loadRules(ruleList);
}
 
Example #6
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 #7
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 #8
Source File: PaceFlowDemo.java    From Sentinel 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 #9
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 #10
Source File: ClusterMetricNodeGenerator.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public static ClusterMetricNode flowToMetricNode(long flowId) {
    FlowRule rule = ClusterFlowRuleManager.getFlowRuleById(flowId);
    if (rule == null) {
        return null;
    }
    ClusterMetric metric = ClusterMetricStatistics.getMetric(flowId);
    if (metric == null) {
        return new ClusterMetricNode().setFlowId(flowId)
            .setResourceName(rule.getResource());
    }
    return new ClusterMetricNode()
        .setFlowId(flowId)
        .setResourceName(rule.getResource())
        .setBlockQps(metric.getAvg(ClusterFlowEvent.BLOCK))
        .setPassQps(metric.getAvg(ClusterFlowEvent.PASS))
        .setTimestamp(TimeUtil.currentTimeMillis());
}
 
Example #11
Source File: FlowRuleEntity.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public FlowRule toRule() {
    FlowRule flowRule = new FlowRule();
    flowRule.setCount(this.count);
    flowRule.setGrade(this.grade);
    flowRule.setResource(this.resource);
    flowRule.setLimitApp(this.limitApp);
    flowRule.setRefResource(this.refResource);
    flowRule.setStrategy(this.strategy);
    if (this.controlBehavior != null) {
        flowRule.setControlBehavior(controlBehavior);
    }
    if (this.warmUpPeriodSec != null) {
        flowRule.setWarmUpPeriodSec(warmUpPeriodSec);
    }
    if (this.maxQueueingTimeMs != null) {
        flowRule.setMaxQueueingTimeMs(maxQueueingTimeMs);
    }
    flowRule.setClusterMode(clusterMode);
    flowRule.setClusterConfig(clusterConfig);
    return flowRule;
}
 
Example #12
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 #13
Source File: EurekaDataSourceTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testEurekaDataSource() throws Exception {
    String url = "http://localhost:" + port + "/eureka";

    EurekaDataSource<List<FlowRule>> eurekaDataSource = new EurekaDataSource(appname, instanceId, Arrays.asList(url)
            , SENTINEL_KEY, new Converter<String, List<FlowRule>>() {
        @Override
        public List<FlowRule> convert(String source) {
            return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            });
        }
    });
    FlowRuleManager.register2Property(eurekaDataSource.getProperty());

    await().timeout(15, TimeUnit.SECONDS)
            .until(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return FlowRuleManager.getRules().size() > 0;
                }
            });
    Assert.assertTrue(FlowRuleManager.getRules().size() > 0);
}
 
Example #14
Source File: SentinelConverterTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonConverter() {
	JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
	List<FlowRule> flowRules = (List<FlowRule>) jsonConverter
			.convert(readFileContent("classpath: flowrule.json"));

	assertThat(flowRules.size()).isEqualTo(1);
	assertThat(flowRules.get(0).getResource()).isEqualTo("resource");
	assertThat(flowRules.get(0).getLimitApp()).isEqualTo("default");
	assertThat(String.valueOf(flowRules.get(0).getCount())).isEqualTo("1.0");
	assertThat(flowRules.get(0).getControlBehavior())
			.isEqualTo(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	assertThat(flowRules.get(0).getStrategy())
			.isEqualTo(RuleConstant.STRATEGY_DIRECT);
	assertThat(flowRules.get(0).getGrade()).isEqualTo(RuleConstant.FLOW_GRADE_QPS);
}
 
Example #15
Source File: PullConsumerDemo.java    From Sentinel 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 #16
Source File: StandaloneRedisDataSourceTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Before
public void buildResource() {
    try {
        // Bind to a random port.
        server = RedisServer.newRedisServer();
        server.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Converter<String, List<FlowRule>> flowConfigParser = buildFlowConfigParser();
    client = RedisClient.create(RedisURI.create(server.getHost(), server.getBindPort()));
    RedisConnectionConfig config = RedisConnectionConfig.builder()
        .withHost(server.getHost())
        .withPort(server.getBindPort())
        .build();
    initRedisRuleData();
    ReadableDataSource<String, List<FlowRule>> redisDataSource = new RedisDataSource<List<FlowRule>>(config,
        ruleKey, channel, flowConfigParser);
    FlowRuleManager.register2Property(redisDataSource.getProperty());
}
 
Example #17
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 #18
Source File: ReactorSphUTest.java    From Sentinel 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 #19
Source File: ModifyClusterFlowRulesCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String namespace = request.getParam("namespace");
    if (StringUtil.isEmpty(namespace)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty namespace"));
    }
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "UTF-8");
        RecordLog.info("[ModifyClusterFlowRulesCommandHandler] Receiving cluster flow rules for namespace <{0}>: {1}", namespace, data);

        List<FlowRule> flowRules = JSONArray.parseArray(data, FlowRule.class);
        ClusterFlowRuleManager.loadRules(namespace, flowRules);

        return CommandResponse.ofSuccess(SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterFlowRulesCommandHandler] Decode cluster flow rules error", e);
        return CommandResponse.ofFailure(e, "decode cluster flow rules error");
    }
}
 
Example #20
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 #21
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public List<FlowRuleEntity> fetchFlowRuleOfMachine(String app, String ip, int port) {
    List<FlowRule> rules = fetchRules(ip, port, FLOW_RULE_TYPE, FlowRule.class);
    if (rules != null) {
        return rules.stream().map(rule -> FlowRuleEntity.fromFlowRule(app, ip, port, rule))
            .collect(Collectors.toList());
    } else {
        return null;
    }
}
 
Example #22
Source File: EnvoySentinelRuleConverterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertToSentinelFlowRules() {
    String domain = "testConvertToSentinelFlowRules";
    EnvoyRlsRule rlsRule = new EnvoyRlsRule();
    rlsRule.setDomain(domain);
    List<ResourceDescriptor> descriptors = new ArrayList<>();
    ResourceDescriptor d1 = new ResourceDescriptor();
    d1.setCount(10d);
    d1.setResources(Collections.singleton(new KeyValueResource("k1", "v1")));
    descriptors.add(d1);
    ResourceDescriptor d2 = new ResourceDescriptor();
    d2.setCount(20d);
    d2.setResources(new HashSet<>(Arrays.asList(
        new KeyValueResource("k2", "v2"),
        new KeyValueResource("k3", "v3")
    )));
    descriptors.add(d2);
    rlsRule.setDescriptors(descriptors);

    List<FlowRule> rules = EnvoySentinelRuleConverter.toSentinelFlowRules(rlsRule);
    final String expectedK1 = domain + SEPARATOR + "k1" + SEPARATOR + "v1";
    FlowRule r1 = rules.stream()
        .filter(e -> e.getResource().equals(expectedK1))
        .findAny()
        .orElseThrow(() -> new AssertionError("the converted rule does not exist, expected key: " + expectedK1));
    assertEquals(10d, r1.getCount(), 0.01);

    final String expectedK2 = domain + SEPARATOR + "k2" + SEPARATOR + "v2" + SEPARATOR + "k3" + SEPARATOR + "v3";
    FlowRule r2 = rules.stream()
        .filter(e -> e.getResource().equals(expectedK2))
        .findAny()
        .orElseThrow(() -> new AssertionError("the converted rule does not exist, expected key: " + expectedK2));
    assertEquals(20d, r2.getCount(), 0.01);
}
 
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: ClusterFlowRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Load flow rules for a specific namespace. The former rules of the namespace will be replaced.
 *
 * @param namespace a valid namespace
 * @param rules rule list
 */
public static void loadRules(String namespace, List<FlowRule> rules) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    NamespaceFlowProperty<FlowRule> property = PROPERTY_MAP.get(namespace);
    if (property != null) {
        property.getProperty().updateValue(rules);
    }
}
 
Example #25
Source File: EnvoyRlsRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void configUpdate(List<EnvoyRlsRule> conf) {
    Map<String, EnvoyRlsRule> ruleMap = generateRuleMap(conf);

    List<FlowRule> flowRules = ruleMap.values().stream()
        .flatMap(e -> EnvoySentinelRuleConverter.toSentinelFlowRules(e).stream())
        .collect(Collectors.toList());

    RULE_MAP.clear();
    RULE_MAP.putAll(ruleMap);
    RecordLog.info("[EnvoyRlsRuleManager] Envoy RLS rules loaded: " + flowRules);

    // Use the "default" namespace.
    ClusterFlowRuleManager.loadRules(ServerConstants.DEFAULT_NAMESPACE, flowRules);
}
 
Example #26
Source File: JarFileDataSourceDemo.java    From Sentinel-Dashboard-Nacos 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 #27
Source File: PaceFlowDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private static void initDefaultFlowRule() {
    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_DEFAULT means requests more than threshold will be rejected immediately.
    rule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);

    rules.add(rule1);
    FlowRuleManager.loadRules(rules);
}
 
Example #28
Source File: CommonFilterMethodTest.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 #29
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));
}
 
Example #30
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));
}