com.ecwid.consul.v1.ConsulClient Java Examples

The following examples show how to use com.ecwid.consul.v1.ConsulClient. 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: DiscoveryBootstrapConfigurationTests.java    From spring-cloud-vault with Apache License 2.0 8 votes vote down vote up
@BeforeClass
public static void beforeClass() {

	assumeTrue(CanConnect.to(new InetSocketAddress(CONSUL_HOST, CONSUL_PORT)));

	ConsulClient client = new ConsulClient();

	Response<List<CatalogService>> response = client.getCatalogService("vault",
			QueryParams.DEFAULT);

	if (response.getValue().isEmpty()) {

		NewService service = new NewService();
		service.setAddress("localhost");
		service.setPort(8200);
		service.setId("vault");
		service.setName("vault");

		client.agentServiceRegister(service);
	}
}
 
Example #2
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 #3
Source File: ConfigWatchTests.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@Test
public void firstCallDoesNotPublishEvent() {
	ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
	this.configProperties.setFormat(FILES);

	GetValue getValue = new GetValue();
	String context = "/config/app.yml";
	ConsulClient consul = mock(ConsulClient.class);
	List<GetValue> getValues = Collections.singletonList(getValue);

	Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
	when(consul.getKVValues(eq(context), anyString(), any(QueryParams.class)))
			.thenReturn(response);

	ConfigWatch watch = new ConfigWatch(this.configProperties, consul,
			new LinkedHashMap<String, Long>());
	watch.setApplicationEventPublisher(eventPublisher);

	watch.watchConfigKeyValues();
	verify(eventPublisher, times(0)).publishEvent(any(RefreshEvent.class));
}
 
Example #4
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Test
public void testStop() {
    LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
    initialIndexes.put("/context", 0L);
    ConfigWatch watch = new ConfigWatch(this.configProperties, new ConsulClient(), bmsAuthClient, initialIndexes);
    watch.start();
    Assert.assertTrue(watch.isRunning());
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // do nothing
        }
    };
    watch.stop(runnable);
    Assert.assertFalse(watch.isRunning());
}
 
Example #5
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Test
public void firstCallDoesNotPublishEvent() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
    this.configProperties.setFormat(FILES);

    GetValue getValue = new GetValue();
    String context = "/config/app.yml";
    ConsulClient consul = mock(ConsulClient.class);
    List<GetValue> getValues = Collections.singletonList(getValue);

    Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
    when(consul.getKVValues(ArgumentMatchers.eq(context), ArgumentMatchers.anyString(),
            ArgumentMatchers.any(QueryParams.class)))
            .thenReturn(response);

    ConfigWatch watch = new ConfigWatch(this.configProperties, consul, bmsAuthClient,
            new LinkedHashMap<String, Long>());
    watch.setApplicationEventPublisher(eventPublisher);

    watch.watchConfigKeyValues(context);
    verify(eventPublisher, times(0)).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #6
Source File: ConsulPropertySourceLocatorTests.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    this.properties = new ConsulProperties();
    this.client = new ConsulClient(this.properties.getHost(),
            this.properties.getPort());
    this.client.deleteKVValues(PREFIX);
    this.client.setKVValue(KEY1, VALUE1);
    this.client.setKVValue(KEY2, VALUE2);

    this.context = new SpringApplicationBuilder(Config.class)
            .web(WebApplicationType.NONE).run("--SPRING_APPLICATION_NAME=" + APP_NAME,
                    "--spring.cloud.consul.config.prefix=" + PREFIX,
                    "--spring.cloud.consul.config.token-enabled=false",
                    "--spring.cloud.consul.config.system-labels=app-test,env-test,d-test",
                    "spring.cloud.consul.config.watch.delay=10");

    this.client = this.context.getBean(ConsulClient.class);
    this.properties = this.context.getBean(ConsulProperties.class);
    this.environment = this.context.getEnvironment();
}
 
Example #7
Source File: TestLock.java    From consul-distributed-lock with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    Lock lock = new Lock(new ConsulClient(), "lock-key", checkTtl);
    try {
        // 获取分布式互斥锁(参数含义:阻塞模式、每次尝试获取锁的间隔500ms、尝试n次)
        if (lock.lock(true, 500L, null)) {
            log.info("Thread {} start!", flag);
            // 处理业务逻辑
            Thread.sleep(new Random().nextInt(5000));
            log.info("Thread {} end!", flag);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }

}
 
Example #8
Source File: ConsulPropertySourceLocatorAppNameCustomizedTests.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
	this.properties = new ConsulProperties();
	this.client = new ConsulClient(this.properties.getHost(),
			this.properties.getPort());
	this.client.deleteKVValues(PREFIX);
	this.client.setKVValue(KEY1, VALUE1);
	this.client.setKVValue(KEY2, VALUE2);

	this.context = new SpringApplicationBuilder(Config.class)
			.web(WebApplicationType.NONE)
			.run("--spring.application.name=testConsulPropertySourceLocatorAppNameCustomized",
					"--spring.cloud.consul.config.name=" + CONFIG_NAME,
					"--spring.cloud.consul.config.prefix=" + ROOT);

	this.client = this.context.getBean(ConsulClient.class);
	this.properties = this.context.getBean(ConsulProperties.class);
	this.environment = this.context.getEnvironment();
}
 
Example #9
Source File: ConsulPropertySourceLocatorFilesTests.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
	this.properties = new ConsulProperties();
	this.client = new ConsulClient(this.properties.getHost(),
			this.properties.getPort());
	this.client.setKVValue(ROOT + APPLICATION_YML, "foo: bar\nmy.baz: ${foo}");
	this.client.setKVValue(ROOT + APPLICATION_DEV_YML,
			"foo: bar-dev\nmy.baz: ${foo}");
	this.client.setKVValue(ROOT + "/master.ref", UUID.randomUUID().toString());
	this.client.setKVValue(ROOT + APP_NAME_PROPS, "foo: bar-app\nmy.baz: ${foo}");
	this.client.setKVValue(ROOT + APP_NAME_DEV_PROPS,
			"foo: bar-app-dev\nmy.baz: ${foo}");

	this.context = new SpringApplicationBuilder(Config.class)
			.web(WebApplicationType.NONE).run("--spring.application.name=" + APP_NAME,
					"--spring.cloud.consul.config.prefix=" + ROOT,
					"--spring.cloud.consul.config.format=FILES",
					"--spring.profiles.active=dev",
					"spring.cloud.consul.config.watch.delay=1");

	this.client = this.context.getBean(ConsulClient.class);
	this.properties = this.context.getBean(ConsulProperties.class);
	this.environment = this.context.getEnvironment();
}
 
Example #10
Source File: ConsulPropertySourceLocatorTests.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
	this.properties = new ConsulProperties();
	this.client = new ConsulClient(this.properties.getHost(),
			this.properties.getPort());
	this.client.deleteKVValues(PREFIX);
	this.client.setKVValue(KEY1, VALUE1);
	this.client.setKVValue(KEY2, VALUE2);

	this.context = new SpringApplicationBuilder(Config.class)
			.web(WebApplicationType.NONE).run("--SPRING_APPLICATION_NAME=" + APP_NAME,
					"--spring.cloud.consul.config.prefix=" + ROOT,
					"spring.cloud.consul.config.watch.delay=10");

	this.client = this.context.getBean(ConsulClient.class);
	this.properties = this.context.getBean(ConsulProperties.class);
	this.environment = this.context.getEnvironment();
}
 
Example #11
Source File: TxleConsulClient.java    From txle with Apache License 2.0 6 votes vote down vote up
public void setAvailableConsulClient() {
    if (consulClient != null) {
        return;
    }
    for (Map.Entry<String, ConsulClient> entry : consulClientMap.entrySet()) {
        try {
            if (entry.getValue().getStatusLeader().getValue() != null) {
                String[] hostPort = entry.getKey().split(":");
                consulProperties.setHost(hostPort[0]);
                consulProperties.setPort(Integer.parseInt(hostPort[1]));
                consulClient = entry.getValue();
                break;
            }
        } catch (Exception e) {
            log.error("Occur an error when executing method 'setAvailableConsulClient'.", e);
            continue;
        }
    }
}
 
Example #12
Source File: ConsulServiceRegistryDisabledTests.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
private void testAutoRegistrationDisabled(String testName, String disableProperty) {
	new WebApplicationContextRunner().withUserConfiguration(TestConfig.class)
			.withPropertyValues("spring.application.name=" + testName,
					disableProperty + "=false", "server.port=0")
			.run(context -> {
				assertThat(context).doesNotHaveBean(ConsulServiceRegistry.class);
				assertThat(context).doesNotHaveBean(HeartbeatProperties.class);

				ConsulClient consul = context.getBean(ConsulClient.class);

				Response<Map<String, Service>> response = consul.getAgentServices();
				Map<String, Service> services = response.getValue();
				Service service = services.get(testName);
				assertThat(service).as("service was registered").isNull();
			});
}
 
Example #13
Source File: ConfigWatch.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
public ConfigWatch(ConsulConfigProperties properties, ConsulClient consul,
		LinkedHashMap<String, Long> initialIndexes, TaskScheduler taskScheduler) {
	this.properties = properties;
	this.consul = consul;
	this.consulIndexes = new LinkedHashMap<>(initialIndexes);
	this.taskScheduler = taskScheduler;
}
 
Example #14
Source File: ConsulHostsSupplierTest.java    From dyno with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeEach() {
    String config = "{" +
            "\"datacenter\": \"test-dc\"," +
            "\"log_level\": \"INFO\"," +
            "\"node_name\": \"foobar\"" +
            "}";
    consulServer = ConsulStarterBuilder.consulStarter().withCustomConfig(config).build().start();
    consulClient = new ConsulClient("127.0.0.1", consulServer.getHttpPort());
}
 
Example #15
Source File: StubRunnerSpringCloudConsulAutoConfiguration.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "registerStubs")
public StubsRegistrar stubsRegistrar(StubRunning stubRunning,
		ConsulClient consulClient, StubMapperProperties stubMapperProperties,
		ConsulDiscoveryProperties consulDiscoveryProperties, InetUtils inetUtils) {
	return new ConsulStubsRegistrar(stubRunning, consulClient, stubMapperProperties,
			consulDiscoveryProperties, inetUtils);
}
 
Example #16
Source File: ConsulConfigAutoConfiguration.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled",
		matchIfMissing = true)
public ConfigWatch configWatch(ConsulConfigProperties properties,
		ConsulPropertySourceLocator locator, ConsulClient consul,
		@Qualifier(CONFIG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
	return new ConfigWatch(properties, consul, locator.getContextIndexes(),
			taskScheduler);
}
 
Example #17
Source File: ConsulRateLimitPreFilterTest.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 5 votes vote down vote up
@BeforeEach
@Override
public void setUp() {
    RateLimiterErrorHandler rateLimiterErrorHandler = mock(RateLimiterErrorHandler.class);
    consulClient = mock(ConsulClient.class);
    this.setRateLimiter(new ConsulRateLimiter(rateLimiterErrorHandler, this.consulClient, this.objectMapper));
    super.setUp();
}
 
Example #18
Source File: TestLock.java    From consul-distributed-lock with Apache License 2.0 5 votes vote down vote up
@Test
public void testLock() throws Exception  {
    ConsulClient consulClient = new ConsulClient();
    CheckTtl checkTtl = new CheckTtl("lock-1", consulClient);
    new Thread(new LockRunner(1, new CheckTtl("lock-1", consulClient))).start();
    new Thread(new LockRunner(2, new CheckTtl("lock-2", consulClient))).start();
    new Thread(new LockRunner(3, new CheckTtl("lock-3", consulClient))).start();
    new Thread(new LockRunner(4, new CheckTtl("lock-4", consulClient))).start();
    new Thread(new LockRunner(5, new CheckTtl("lock-5", consulClient))).start();
    Thread.sleep(30000L);
}
 
Example #19
Source File: ConsulStubsRegistrar.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
public ConsulStubsRegistrar(StubRunning stubRunning, ConsulClient consulClient,
		StubMapperProperties stubMapperProperties,
		ConsulDiscoveryProperties consulDiscoveryProperties, InetUtils inetUtils) {
	this.stubRunning = stubRunning;
	this.consulClient = consulClient;
	this.stubMapperProperties = stubMapperProperties;
	this.consulDiscoveryProperties = consulDiscoveryProperties;
	this.inetUtils = inetUtils;
}
 
Example #20
Source File: ConsulServiceRegistryAutoConfiguration.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient,
		ConsulDiscoveryProperties properties, HeartbeatProperties heartbeatProperties,
		@Autowired(required = false) TtlScheduler ttlScheduler) {
	return new ConsulServiceRegistry(consulClient, properties, ttlScheduler,
			heartbeatProperties);
}
 
Example #21
Source File: ConsulPropertySource.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
public ConsulPropertySource(String context, ConsulClient source,
		ConsulConfigProperties configProperties) {
	super(context, source);
	this.context = context;
	this.configProperties = configProperties;

}
 
Example #22
Source File: ConsulCatalogWatchAutoConfiguration.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public ConsulCatalogWatch consulCatalogWatch(
		ConsulDiscoveryProperties discoveryProperties, ConsulClient consulClient,
		@Qualifier(CATALOG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
	return new ConsulCatalogWatch(discoveryProperties, consulClient, taskScheduler);
}
 
Example #23
Source File: ConsulUtils.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static ConsulClient createClient(String apiAddress, int apiPort, TlsConfiguration tlsConfiguration) throws Exception {
    HttpClient httpClient = createHttpClient(tlsConfiguration.getClientCert(), tlsConfiguration.getClientKey(), tlsConfiguration.getServerCert());
    ConsulRawClient rawClient = new ConsulRawClient("https://" + apiAddress + ':' + apiPort, httpClient);
    Field agentAddress = ReflectionUtils.findField(ConsulRawClient.class, "agentAddress");
    ReflectionUtils.makeAccessible(agentAddress);
    ReflectionUtils.setField(agentAddress, rawClient, "https://" + apiAddress + ':' + apiPort + "/consul");
    return new ConsulClient(rawClient);
}
 
Example #24
Source File: ConsulRegistryRepository.java    From saluki with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    consulClient = new ConsulClient(agentHost);
    executor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                log.info("begin to load from registry");
                servicesPassing.clear();
                servicesFailing.clear();
                loadAllServiceFromConsul();
            } catch (Throwable e) {
                log.error(e.getMessage(), e);
            }
        }
    }, 0, 1, TimeUnit.MINUTES);
}
 
Example #25
Source File: ConsulServiceRegistry.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
public ConsulServiceRegistry(ConsulClient client,
		ConsulDiscoveryProperties properties, TtlScheduler ttlScheduler,
		HeartbeatProperties heartbeatProperties) {
	this.client = client;
	this.properties = properties;
	this.ttlScheduler = ttlScheduler;
	this.heartbeatProperties = heartbeatProperties;
}
 
Example #26
Source File: ConsulRegistry.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public ConsulRegistry(URL url) {
    super(url);
    if (url.isAnyHost()) {
        throw new IllegalStateException("registry address == null");
    }
    consulClient = new ConsulClient(url.getHost(), url.getPort());
}
 
Example #27
Source File: TestSemaphore.java    From consul-distributed-lock with Apache License 2.0 5 votes vote down vote up
@Test
public void testSemaphore() throws Exception {
    ConsulClient consulClient = new ConsulClient();
    new Thread(new SemaphoreRunner(1, new CheckTtl("semaphore-1", consulClient))).start();
    new Thread(new SemaphoreRunner(2, new CheckTtl("semaphore-2", consulClient))).start();
    new Thread(new SemaphoreRunner(3, new CheckTtl("semaphore-3", consulClient))).start();
    new Thread(new SemaphoreRunner(4, new CheckTtl("semaphore-4", consulClient))).start();
    new Thread(new SemaphoreRunner(5, new CheckTtl("semaphore-5", consulClient))).start();
    new Thread(new SemaphoreRunner(6, new CheckTtl("semaphore-6", consulClient))).start();
    new Thread(new SemaphoreRunner(7, new CheckTtl("semaphore-7", consulClient))).start();
    new Thread(new SemaphoreRunner(8, new CheckTtl("semaphore-8", consulClient))).start();
    new Thread(new SemaphoreRunner(9, new CheckTtl("semaphore-9", consulClient))).start();
    new Thread(new SemaphoreRunner(10, new CheckTtl("semaphore-10", consulClient))).start();
    Thread.sleep(50000L);
}
 
Example #28
Source File: HealthServiceInformer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public HealthServiceInformer(String serviceName, String tag, ConsulClient consulClient, ConsulRegistryProperties properties) {
    this.serviceName = serviceName;
    this.tag = tag;
    this.consulClient = consulClient;
    this.properties = properties;
    this.listeners = new ArrayList<>();
}
 
Example #29
Source File: ConsulController.java    From james with Apache License 2.0 5 votes vote down vote up
private void setupConsulWatcher(ConsulControllerConfiguration configuration,
                                InformationPointService informationPointService) {
    ConsulClient client = new ConsulClient(configuration.getHost(), configuration.getPort());
    ConsulWatchedConfigurationSource configurationSource =
            new ConsulWatchedConfigurationSource(configuration.getFolderPath(), client);
    DynamicWatchedConfiguration dynamicConfig = new DynamicWatchedConfiguration(configurationSource);

    dynamicConfig.addConfigurationListener(event -> {
        if (!event.isBeforeUpdate()) {
            switch (event.getType()) {
                case AbstractConfiguration.EVENT_ADD_PROPERTY:
                    onInformationPointAdded(event, informationPointService);
                    break;
                case AbstractConfiguration.EVENT_SET_PROPERTY:
                    onInformationPointModified(event, informationPointService);
                    break;
                case AbstractConfiguration.EVENT_CLEAR_PROPERTY:
                    onInformationPointRemoved(event, informationPointService);
                    break;
                case AbstractConfiguration.EVENT_CLEAR:
                    onInformationPointsCleared(informationPointService);
                    break;
                default:
                    LOG.debug(() -> "Unsupported event type: " + event.getType());
            }
        }
    });
    configurationSource.startAsync();

    ConcurrentCompositeConfiguration compositeConfig = new ConcurrentCompositeConfiguration();
    compositeConfig.addConfiguration(dynamicConfig, "consul-dynamic");
    ConfigurationManager.install(compositeConfig);
}
 
Example #30
Source File: TtlScheduler.java    From saluki with Apache License 2.0 5 votes vote down vote up
public TtlScheduler(ConsulClient client){
    this.client = client;
    heartbeatServiceExecutor.scheduleAtFixedRate(new ConsulHeartbeatServiceTask(), ConsulConstants.HEARTBEAT_CIRCLE,
                                                 ConsulConstants.HEARTBEAT_CIRCLE, TimeUnit.MILLISECONDS);
    heartbeatSessionExecutor.scheduleAtFixedRate(new ConsulHeartbeatSessionTask(), ConsulConstants.HEARTBEAT_CIRCLE,
                                                 ConsulConstants.HEARTBEAT_CIRCLE, TimeUnit.MILLISECONDS);
}