org.springframework.boot.test.context.runner.WebApplicationContextRunner#com.ecwid.consul.v1.ConsulClient源码实例Demo

下面列出了org.springframework.boot.test.context.runner.WebApplicationContextRunner#com.ecwid.consul.v1.ConsulClient 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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);
	}
}
 
源代码2 项目: txle   文件: TxleConsulClient.java
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;
        }
    }
}
 
源代码3 项目: spring-cloud-consul   文件: ConfigWatchTests.java
@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));
}
 
源代码4 项目: spring-cloud-formula   文件: ConfigWatchTests.java
@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());
}
 
源代码5 项目: spring-cloud-formula   文件: ConfigWatchTests.java
@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));
}
 
@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();
}
 
@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();
}
 
源代码8 项目: Sentinel   文件: ConsulDataSourceTest.java
@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());
}
 
源代码9 项目: saluki   文件: ConsulRegistryRepository.java
@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);
}
 
@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();
}
 
源代码11 项目: consul-distributed-lock   文件: TestLock.java
@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();
    }

}
 
@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();
}
 
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();
			});
}
 
@Before
public void setup() {
	this.properties = new ConsulProperties();
	this.prefix = "consulPropertySourceTests"
			+ new Random().nextInt(Integer.MAX_VALUE);
	this.client = new ConsulClient(this.properties.getHost(),
			this.properties.getPort());
}
 
源代码15 项目: txle   文件: TxleConsulClient.java
private void initConsulCluster() {
    try {
        if (consulServers != null && consulServers.length() > 0) {
            for (String hostPorts : consulServers.split(",")) {
                String[] hostPort = hostPorts.trim().split(":");
                consulClientMap.put(hostPorts, new ConsulClient(hostPort[0], Integer.parseInt(hostPort[1])));
            }
        }
    } catch (Exception e) {
        // It's not a strong dependency to Consul.
        log.error("Could not connect to Consul, servers = [{}].", consulServers, e);
    }
}
 
源代码16 项目: cloudbreak   文件: ConsulKeyValueService.java
public void deleteAlert(Cluster cluster, PrometheusAlert alert) {
    ClusterManager ambari = cluster.getClusterManager();
    try {
        TlsConfiguration tlsConfig = tlsSecurityService.getTls(cluster.getId());
        ConsulClient consulClient = ConsulUtils.createClient(ambari.getHost(), cluster.getPort(), tlsConfig);
        String alertKey = getKeyNameForAlert(alert);
        consulClient.deleteKVValue(alertKey);
        LOGGER.debug("Alert has been removed from Consul KV store with name: '{}' on host: '{}'.", alertKey, ambari.getHost());
    } catch (Exception e) {
        LOGGER.error("Alert could not be deleted from Consul KV store: {}", e.getMessage());
    }
}
 
源代码17 项目: spring-cloud-formula   文件: ConfigWatch.java
public ConfigWatch(ConsulConfigProperties properties, ConsulClient consul, BmsAuthClient bmsAuthClient,
                   LinkedHashMap<String, Long> initialIndexes, List<ThreadPoolTaskScheduler> taskSchedulers) {
    this.properties = properties;
    this.consul = consul;
    this.consulIndexes = new LinkedHashMap<>(initialIndexes);
    this.watchFutures = new ScheduledFuture<?>[consulIndexes.size()];
    this.bmsAuthClient = bmsAuthClient;
    if (taskSchedulers == null) {
        this.taskSchedulers = getTaskSchedulers();
    } else {
        this.taskSchedulers = taskSchedulers;
    }
}
 
public ConsulPropertySourceLocator(ConsulClient consul,
                                   BmsAuthClient bmsAuthClient,
                                   ConsulConfigProperties properties) {
    this.consul = consul;
    this.bmsAuthClient = bmsAuthClient;
    this.properties = properties;
}
 
@Bean
@ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled",
        matchIfMissing = true)
public ConfigWatch configWatch(ConsulConfigProperties properties, BmsAuthClient bmsAuthClient,
                               ConsulPropertySourceLocator locator, ConsulClient consul) {
    return new ConfigWatch(properties, consul, bmsAuthClient, locator.getContextIndexes());
}
 
@Bean
@Primary
public ConsulClient consulClient(ConsulProperties consulProperties,
                                 ConsulConfigProperties consulConfigProperties) {
    final int agentPort = consulProperties.getPort();
    final String agentHost = !StringUtils.isEmpty(consulProperties.getScheme())
            ? consulProperties.getScheme() + "://" + consulProperties.getHost()
            : consulProperties.getHost();

    logger.info("Init consul host: " + agentHost + " port: " + agentPort);
    if (consulProperties.getTls() != null) {
        ConsulProperties.TLSConfig tls = consulProperties.getTls();
        TLSConfig tlsConfig = new TLSConfig(
                tls.getKeyStoreInstanceType(),
                tls.getCertificatePath(),
                tls.getCertificatePassword(),
                tls.getKeyStorePath(),
                tls.getKeyStorePassword()
        );
        return new ConsulClient(agentHost, agentPort, tlsConfig);
    }
    HttpRequestInterceptor httpRequestInterceptor = new BmsCommonInterceptor();
    BmsHttpTransport httpTransport = new BmsHttpTransport(httpRequestInterceptor);
    ConsulRawClient rawClient = new ConsulRawClient(httpTransport.getHttpClient(),
            agentHost, agentPort, consulConfigProperties.getPath());
    return new ConsulClient(rawClient);
}
 
public ConsulPropertySource(String context, ConsulClient source, BmsAuthClient bmsAuthClient,
                            ConsulConfigProperties configProperties) {
    super(context, source);
    this.context = context;
    this.configProperties = configProperties;
    this.bmsAuthClient = bmsAuthClient;
}
 
@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(ConsulConfigBootstrapConfiguration.class)
            .web(WebApplicationType.NONE).run("--spring.application.name=" + APP_NAME,
                    "--spring.cloud.consul.config.prefix=" + ROOT,
                    "--spring.cloud.consul.config.format=FILES",
                    "--spring.cloud.consul.config.token-enabled=false",
                    "--spring.cloud.consul.config.default-context=application",
                    "--spring.cloud.consul.config.system-labels=application-dev,testFilesFormat," +
                            "testFilesFormat-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();
}
 
源代码23 项目: spring-cloud-formula   文件: ConfigWatchTests.java
private void setupWatch(ApplicationEventPublisher eventPublisher, String context,
                        Response<List<GetValue>> response) {
    ConsulClient consul = mock(ConsulClient.class);

    when(consul.getKVValues(ArgumentMatchers.eq(context), nullable(String.class),
            ArgumentMatchers.any(QueryParams.class))).thenReturn(response);

    LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
    initialIndexes.put(context, 0L);
    startWatch(eventPublisher, consul, initialIndexes);
}
 
源代码24 项目: spring-cloud-formula   文件: ConfigWatchTests.java
private void setupWatchThrowException(ApplicationEventPublisher eventPublisher, String context) {
    ConsulClient consul = mock(ConsulClient.class);
    OperationException operationException = new OperationException(403, null, null);
    when(consul.getKVValues(ArgumentMatchers.eq(context), nullable(String.class),
            ArgumentMatchers.any(QueryParams.class))).thenThrow(operationException);

    LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
    initialIndexes.put(context, 0L);
    startWatch(eventPublisher, consul, initialIndexes);
}
 
源代码25 项目: spring-cloud-formula   文件: ConfigWatchTests.java
private void setupWatchWithIllegalIndex(ApplicationEventPublisher eventPublisher, String context,
                                        Response<List<GetValue>> response) {
    ConsulClient consul = mock(ConsulClient.class);

    when(consul.getKVValues(ArgumentMatchers.eq(context), nullable(String.class),
            ArgumentMatchers.any(QueryParams.class))).thenReturn(response);

    LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
    initialIndexes.put(context, -1L);
    startWatch(eventPublisher, consul, initialIndexes);
}
 
源代码26 项目: spring-cloud-formula   文件: ConfigWatchTests.java
@Test
public void testGetMethods() {
    LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
    initialIndexes.put("/context", 0L);
    ConfigWatch watch = new ConfigWatch(this.configProperties, new ConsulClient(), bmsAuthClient, initialIndexes);
    Assert.assertEquals(0, watch.getPhase());
    Assert.assertEquals(true, watch.isAutoStartup());
}
 
源代码27 项目: garmadon   文件: ConsulConnection.java
/**
 * Fetches healthy garmadon forwarder end points from consul.
 */
private List<HealthService> getHealthyEndPoints() {
    ConsulClient client = new ConsulClient("localhost");

    HealthServicesRequest request = HealthServicesRequest.newBuilder()
            .setPassing(true)
            .setQueryParams(QueryParams.DEFAULT)
            .build();
    Response<List<HealthService>> healthyServices = client.getHealthServices(serviceName, request);

    return healthyServices.getValue();
}
 
源代码28 项目: garmadon   文件: HiveDriverConsul.java
/**
 * Fetches healthy service nodes
 */
private List<HealthService> getHealthyEndPoints(String serviceName) {
    ConsulClient client = new ConsulClient("localhost");

    HealthServicesRequest request = HealthServicesRequest.newBuilder()
        .setPassing(true)
        .setQueryParams(QueryParams.DEFAULT)
        .build();
    Response<List<HealthService>> healthyServices = client.getHealthServices(serviceName, request);

    return healthyServices.getValue();
}
 
源代码29 项目: nacos-sync   文件: ConsulServerHolder.java
@Override
ConsulClient createServer(String clusterId, Supplier<String> serverAddressSupplier, String namespace) throws Exception {
    String serverAddress = serverAddressSupplier.get();
    serverAddress = serverAddress.startsWith(HTTP) ? serverAddress : HTTP + serverAddress;
    URL url = new URL(serverAddress);
    return new ConsulClient(url.getHost(), url.getPort());
}
 
源代码30 项目: nacos-sync   文件: NacosSyncToConsulServiceImpl.java
@Override
public boolean delete(TaskDO taskDO) {
    try {

        NamingService sourceNamingService =
            nacosServerHolder.get(taskDO.getSourceClusterId(), taskDO.getGroupName());
        ConsulClient consulClient = consulServerHolder.get(taskDO.getDestClusterId(), taskDO.getGroupName());

        sourceNamingService.unsubscribe(taskDO.getServiceName(), nacosListenerMap.get(taskDO.getTaskId()));

        // 删除目标集群中同步的实例列表
        Response<List<HealthService>> serviceResponse =
            consulClient.getHealthServices(taskDO.getServiceName(), true, QueryParams.DEFAULT);
        List<HealthService> healthServices = serviceResponse.getValue();
        for (HealthService healthService : healthServices) {

            if (needDelete(ConsulUtils.transferMetadata(healthService.getService().getTags()), taskDO)) {
                consulClient.agentServiceDeregister(healthService.getService().getId());
            }
        }
    } catch (Exception e) {
        log.error("delete a task from nacos to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR);
        return false;
    }
    return true;
}