com.alibaba.csp.sentinel.datasource.Converter Java Examples

The following examples show how to use com.alibaba.csp.sentinel.datasource.Converter. 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: ApolloDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the Apollo data source
 *
 * @param namespaceName        the namespace name in Apollo, should not be null or empty
 * @param ruleKey              the rule key in the namespace, should not be null or empty
 * @param defaultRuleValue     the default rule value when the ruleKey is not found or any error
 *                             occurred
 * @param parser               the parser to transform string configuration to actual flow rules
 */
public ApolloDataSource(String namespaceName, String ruleKey, String defaultRuleValue,
                        Converter<String, T> parser) {
    super(parser);

    Preconditions.checkArgument(!Strings.isNullOrEmpty(namespaceName), "Namespace name could not be null or empty");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(ruleKey), "RuleKey could not be null or empty!");

    this.ruleKey = ruleKey;
    this.defaultRuleValue = defaultRuleValue;

    this.config = ConfigService.getConfig(namespaceName);

    initialize();

    RecordLog.info(String.format("Initialized rule for namespace: %s, rule key: %s", namespaceName, ruleKey));
}
 
Example #2
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 #3
Source File: ConsulDataSourceTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    this.consul = ConsulStarterBuilder.consulStarter()
        .build()
        .start();
    int port = consul.getHttpPort();
    String host = "127.0.0.1";
    client = new ConsulClient(host, port);
    Converter<String, List<FlowRule>> flowConfigParser = buildFlowConfigParser();
    String flowRulesJson =
        "[{\"resource\":\"test\", \"limitApp\":\"default\", \"grade\":1, \"count\":\"0.0\", \"strategy\":0, "
            + "\"refResource\":null, "
            +
            "\"controlBehavior\":0, \"warmUpPeriodSec\":10, \"maxQueueingTimeMs\":500, \"controller\":null}]";
    initConsulRuleData(flowRulesJson);
    rules = flowConfigParser.convert(flowRulesJson);
    consulDataSource = new ConsulDataSource<>(host, port, ruleKey, waitTimeoutInSecond, flowConfigParser);
    FlowRuleManager.register2Property(consulDataSource.getProperty());
}
 
Example #4
Source File: ApolloDataSource.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the Apollo data source
 *
 * @param namespaceName        the namespace name in Apollo, should not be null or empty
 * @param ruleKey              the rule key in the namespace, should not be null or empty
 * @param defaultRuleValue     the default rule value when the ruleKey is not found or any error
 *                             occurred
 * @param parser               the parser to transform string configuration to actual flow rules
 */
public ApolloDataSource(String namespaceName, String ruleKey, String defaultRuleValue,
                        Converter<String, T> parser) {
    super(parser);

    Preconditions.checkArgument(!Strings.isNullOrEmpty(namespaceName), "Namespace name could not be null or empty");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(ruleKey), "RuleKey could not be null or empty!");

    this.ruleKey = ruleKey;
    this.defaultRuleValue = defaultRuleValue;

    this.config = ConfigService.getConfig(namespaceName);

    initialize();

    RecordLog.info(String.format("Initialized rule for namespace: %s, rule key: %s", namespaceName, ruleKey));
}
 
Example #5
Source File: ApolloDataSourceFactoryBeanTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
public void testApolloFactoryBean() throws Exception {
	ApolloDataSourceFactoryBean factoryBean = spy(new ApolloDataSourceFactoryBean());

	Converter converter = mock(JsonConverter.class);

	factoryBean.setDefaultFlowRuleValue(defaultFlowValue);
	factoryBean.setFlowRulesKey(flowRuleKey);
	factoryBean.setNamespaceName(namespace);
	factoryBean.setConverter(converter);

	ApolloDataSource apolloDataSource = mock(ApolloDataSource.class);

	when(apolloDataSource.readSource()).thenReturn("{}");
	doReturn(apolloDataSource).when(factoryBean).getObject();

	assertThat(factoryBean.getObject()).isEqualTo(apolloDataSource);
	assertThat(factoryBean.getObject().readSource()).isEqualTo("{}");
	assertThat(factoryBean.getConverter()).isEqualTo(converter);
	assertThat(factoryBean.getFlowRulesKey()).isEqualTo(flowRuleKey);
	assertThat(factoryBean.getNamespaceName()).isEqualTo(namespace);
	assertThat(factoryBean.getDefaultFlowRuleValue()).isEqualTo(defaultFlowValue);
}
 
Example #6
Source File: ZookeeperDataSourceFactoryBeanTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
public void testZKWithoutPathFactoryBean() throws Exception {
	ZookeeperDataSourceFactoryBean factoryBean = spy(
			ZookeeperDataSourceFactoryBean.class);

	Converter converter = mock(XmlConverter.class);

	ZookeeperDataSource zookeeperDataSource = mock(ZookeeperDataSource.class);

	factoryBean.setConverter(converter);
	factoryBean.setDataId(dataId);
	factoryBean.setGroupId(groupId);
	factoryBean.setServerAddr(serverAddr);

	when(zookeeperDataSource.readSource()).thenReturn("{}");
	doReturn(zookeeperDataSource).when(factoryBean).getObject();

	assertThat(factoryBean.getObject()).isEqualTo(zookeeperDataSource);
	assertThat(factoryBean.getObject().readSource()).isEqualTo("{}");
	assertThat(factoryBean.getDataId()).isEqualTo(dataId);
	assertThat(factoryBean.getConverter()).isEqualTo(converter);
	assertThat(factoryBean.getGroupId()).isEqualTo(groupId);
	assertThat(factoryBean.getServerAddr()).isEqualTo(serverAddr);
}
 
Example #7
Source File: StandaloneRedisDataSourceTest.java    From Sentinel-Dashboard-Nacos 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 #8
Source File: EtcdDataSource.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Create an etcd data-source. The connection configuration will be retrieved from {@link EtcdConfig}.
 *
 * @param key    config key
 * @param parser data parser
 */
public EtcdDataSource(String key, Converter<String, T> parser) {
    super(parser);
    if (!EtcdConfig.isAuthEnable()) {
        this.client = Client.builder()
            .endpoints(EtcdConfig.getEndPoints().split(",")).build();
    } else {
        this.client = Client.builder()
            .endpoints(EtcdConfig.getEndPoints().split(","))
            .user(ByteSequence.from(EtcdConfig.getUser(), charset))
            .password(ByteSequence.from(EtcdConfig.getPassword(), charset))
            .authority(EtcdConfig.getAuthority())
            .build();
    }
    this.key = key;
    loadInitialConfig();
    initWatcher();
}
 
Example #9
Source File: ZookeeperDataSourceFactoryBeanTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
public void testZKWithPathFactoryBean() throws Exception {
	ZookeeperDataSourceFactoryBean factoryBean = spy(
			ZookeeperDataSourceFactoryBean.class);

	Converter converter = mock(XmlConverter.class);

	ZookeeperDataSource zookeeperDataSource = mock(ZookeeperDataSource.class);

	factoryBean.setConverter(converter);
	factoryBean.setPath(path);
	factoryBean.setServerAddr(serverAddr);

	when(zookeeperDataSource.readSource()).thenReturn("{}");
	doReturn(zookeeperDataSource).when(factoryBean).getObject();

	assertThat(factoryBean.getObject()).isEqualTo(zookeeperDataSource);
	assertThat(factoryBean.getObject().readSource()).isEqualTo("{}");
	assertThat(factoryBean.getConverter()).isEqualTo(converter);
	assertThat(factoryBean.getPath()).isEqualTo(path);
	assertThat(factoryBean.getServerAddr()).isEqualTo(serverAddr);
}
 
Example #10
Source File: FileRefreshableDataSourceFactoryBeanTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
private Converter buildConverter() {
	return 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;
		}
	};
}
 
Example #11
Source File: NacosDataSourceFactoryBeanTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
public void testNacosFactoryBeanServerAddr() throws Exception {
	NacosDataSourceFactoryBean factoryBean = spy(new NacosDataSourceFactoryBean());

	Converter converter = mock(SentinelConverter.class);

	factoryBean.setDataId(dataId);
	factoryBean.setGroupId(groupId);
	factoryBean.setServerAddr(serverAddr);
	factoryBean.setConverter(converter);

	NacosDataSource nacosDataSource = mock(NacosDataSource.class);

	doReturn(nacosDataSource).when(factoryBean).getObject();
	when(nacosDataSource.readSource()).thenReturn("{}");

	assertThat(factoryBean.getObject()).isEqualTo(nacosDataSource);
	assertThat(factoryBean.getObject().readSource()).isEqualTo("{}");
	assertThat(factoryBean.getConverter()).isEqualTo(converter);
	assertThat(factoryBean.getDataId()).isEqualTo(dataId);
	assertThat(factoryBean.getGroupId()).isEqualTo(groupId);
	assertThat(factoryBean.getServerAddr()).isEqualTo(serverAddr);
}
 
Example #12
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 #13
Source File: EurekaDataSource.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public EurekaDataSource(String appId, String instanceId, List<String> serviceUrls, String ruleKey,
                        Converter<String, T> configParser, long refreshMs, int connectTimeoutMills,
                        int readTimeoutMills) {
    super(configParser, refreshMs);
    AssertUtil.notNull(appId, "appId can't be null");
    AssertUtil.notNull(instanceId, "instanceId can't be null");
    AssertUtil.assertNotEmpty(serviceUrls, "serviceUrls can't be empty");
    AssertUtil.notNull(ruleKey, "ruleKey can't be null");
    AssertUtil.assertState(connectTimeoutMills > 0, "connectTimeoutMills must be greater than 0");
    AssertUtil.assertState(readTimeoutMills > 0, "readTimeoutMills must be greater than 0");

    this.appId = appId;
    this.instanceId = instanceId;
    this.serviceUrls = ensureEndWithSlash(serviceUrls);
    AssertUtil.assertNotEmpty(this.serviceUrls, "No available service url");
    this.ruleKey = ruleKey;
    this.connectTimeoutMills = connectTimeoutMills;
    this.readTimeoutMills = readTimeoutMills;
}
 
Example #14
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 #15
Source File: NacosDataSourceFactoryBeanTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testNacosFactoryBeanProperties() throws Exception {
	NacosDataSourceFactoryBean factoryBean = spy(new NacosDataSourceFactoryBean());

	Converter converter = mock(SentinelConverter.class);

	factoryBean.setDataId(dataId);
	factoryBean.setGroupId(groupId);
	factoryBean.setAccessKey(accessKey);
	factoryBean.setSecretKey(secretKey);
	factoryBean.setEndpoint(endpoint);
	factoryBean.setNamespace(namespace);
	factoryBean.setConverter(converter);

	NacosDataSource nacosDataSource = mock(NacosDataSource.class);

	doReturn(nacosDataSource).when(factoryBean).getObject();
	when(nacosDataSource.readSource()).thenReturn("{}");

	assertThat(factoryBean.getObject()).isEqualTo(nacosDataSource);
	assertThat(factoryBean.getObject().readSource()).isEqualTo("{}");
	assertThat(factoryBean.getConverter()).isEqualTo(converter);
	assertThat(factoryBean.getDataId()).isEqualTo(dataId);
	assertThat(factoryBean.getGroupId()).isEqualTo(groupId);
	assertThat(factoryBean.getNamespace()).isEqualTo(namespace);
	assertThat(factoryBean.getEndpoint()).isEqualTo(endpoint);
	assertThat(factoryBean.getAccessKey()).isEqualTo(accessKey);
	assertThat(factoryBean.getSecretKey()).isEqualTo(secretKey);
}
 
Example #16
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 #17
Source File: ZookeeperDataSourceTest.java    From Sentinel-Dashboard-Nacos 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 #18
Source File: ZookeeperDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * This constructor is Nacos-style.
 */
public ZookeeperDataSource(final String serverAddr, final String groupId, final String dataId,
                           Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) {
        throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], groupId=[%s], dataId=[%s]", serverAddr, groupId, dataId));
    }
    this.path = getPath(groupId, dataId);

    init(serverAddr, null);
}
 
Example #19
Source File: ZookeeperDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * This constructor adds authentication information.
 */
public ZookeeperDataSource(final String serverAddr, final List<AuthInfo> authInfos, final String groupId, final String dataId,
                           Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) {
        throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], authInfos=[%s], groupId=[%s], dataId=[%s]", serverAddr, authInfos, groupId, dataId));
    }
    this.path = getPath(groupId, dataId);

    init(serverAddr, authInfos);
}
 
Example #20
Source File: NacosDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param properties properties for construct {@link ConfigService} using {@link NacosFactory#createConfigService(Properties)}
 * @param groupId    group ID, cannot be empty
 * @param dataId     data ID, cannot be empty
 * @param parser     customized data parser, cannot be empty
 */
public NacosDataSource(final Properties properties, final String groupId, final String dataId,
                       Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) {
        throw new IllegalArgumentException(String.format("Bad argument: groupId=[%s], dataId=[%s]",
            groupId, dataId));
    }
    AssertUtil.notNull(properties, "Nacos properties must not be null, you could put some keys from PropertyKeyConst");
    this.groupId = groupId;
    this.dataId = dataId;
    this.properties = properties;
    this.configListener = new Listener() {
        @Override
        public Executor getExecutor() {
            return pool;
        }

        @Override
        public void receiveConfigInfo(final String configInfo) {
            RecordLog.info(String.format("[NacosDataSource] New property value received for (properties: %s) (dataId: %s, groupId: %s): %s",
                properties, dataId, groupId, configInfo));
            T newValue = NacosDataSource.this.parser.convert(configInfo);
            // Update the new value to the property.
            getProperty().updateValue(newValue);
        }
    };
    initNacosListener();
    loadInitialConfig();
}
 
Example #21
Source File: ZookeeperDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public ZookeeperDataSource(final String serverAddr, final String path, Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(path)) {
        throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], path=[%s]", serverAddr, path));
    }
    this.path = path;

    init(serverAddr, null);
}
 
Example #22
Source File: RedisDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor of {@code RedisDataSource}.
 *
 * @param connectionConfig Redis connection config
 * @param ruleKey          data key in Redis
 * @param channel          channel to subscribe in Redis
 * @param parser           customized data parser, cannot be empty
 */
public RedisDataSource(RedisConnectionConfig connectionConfig, String ruleKey, String channel,
                       Converter<String, T> parser) {
    super(parser);
    AssertUtil.notNull(connectionConfig, "Redis connection config can not be null");
    AssertUtil.notEmpty(ruleKey, "Redis ruleKey can not be empty");
    AssertUtil.notEmpty(channel, "Redis subscribe channel can not be empty");
    this.redisClient = getRedisClient(connectionConfig);
    this.ruleKey = ruleKey;
    loadInitialConfig();
    subscribeFromChannel(channel);
}
 
Example #23
Source File: SentinelModeRedisDataSourceTest.java    From Sentinel 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 #24
Source File: ConsulDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor of {@code ConsulDataSource}.
 *
 * @param parser       customized data parser, cannot be empty
 * @param host         consul agent host
 * @param port         consul agent port
 * @param ruleKey      data key in Consul
 * @param watchTimeout request for querying data will be blocked until new data or timeout. The unit is second (s)
 */
public ConsulDataSource(String host, int port, String ruleKey, int watchTimeout, Converter<String, T> parser) {
    super(parser);
    AssertUtil.notNull(host, "Consul host can not be null");
    AssertUtil.notEmpty(ruleKey, "Consul ruleKey can not be empty");
    AssertUtil.isTrue(watchTimeout >= 0, "watchTimeout should not be negative");
    this.client = new ConsulClient(host, port);
    this.address = host + ":" + port;
    this.ruleKey = ruleKey;
    this.watchTimeout = watchTimeout;
    loadInitialConfig();
    startKVWatcher();
}
 
Example #25
Source File: ZookeeperDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public ZookeeperDataSource(final String serverAddr, final String path, Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(path)) {
        throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], path=[%s]", serverAddr, path));
    }
    this.path = path;

    init(serverAddr, null);
}
 
Example #26
Source File: ZookeeperDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * This constructor is Nacos-style.
 */
public ZookeeperDataSource(final String serverAddr, final String groupId, final String dataId,
                           Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) {
        throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], groupId=[%s], dataId=[%s]", serverAddr, groupId, dataId));
    }
    this.path = getPath(groupId, dataId);

    init(serverAddr, null);
}
 
Example #27
Source File: ZookeeperDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * This constructor adds authentication information.
 */
public ZookeeperDataSource(final String serverAddr, final List<AuthInfo> authInfos, final String groupId, final String dataId,
                           Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) {
        throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], authInfos=[%s], groupId=[%s], dataId=[%s]", serverAddr, authInfos, groupId, dataId));
    }
    this.path = getPath(groupId, dataId);

    init(serverAddr, authInfos);
}
 
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: SpringCloudConfigDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public SpringCloudConfigDataSource(final String ruleKey, Converter<String, T> converter) {
    super(converter);
    if (StringUtil.isBlank(ruleKey)) {
        throw new IllegalArgumentException(String.format("Bad argument: ruleKey=[%s]", ruleKey));
    }

    this.ruleKey = ruleKey;
    loadInitialConfig();
    initListener();
}
 
Example #30
Source File: NacosDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param properties properties for construct {@link ConfigService} using {@link NacosFactory#createConfigService(Properties)}
 * @param groupId    group ID, cannot be empty
 * @param dataId     data ID, cannot be empty
 * @param parser     customized data parser, cannot be empty
 */
public NacosDataSource(final Properties properties, final String groupId, final String dataId,
                       Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) {
        throw new IllegalArgumentException(String.format("Bad argument: groupId=[%s], dataId=[%s]",
            groupId, dataId));
    }
    AssertUtil.notNull(properties, "Nacos properties must not be null, you could put some keys from PropertyKeyConst");
    this.groupId = groupId;
    this.dataId = dataId;
    this.properties = properties;
    this.configListener = new Listener() {
        @Override
        public Executor getExecutor() {
            return pool;
        }

        @Override
        public void receiveConfigInfo(final String configInfo) {
            RecordLog.info(String.format("[NacosDataSource] New property value received for (properties: %s) (dataId: %s, groupId: %s): %s",
                properties, dataId, groupId, configInfo));
            T newValue = NacosDataSource.this.parser.convert(configInfo);
            // Update the new value to the property.
            getProperty().updateValue(newValue);
        }
    };
    initNacosListener();
    loadInitialConfig();
}