Java Code Examples for org.apache.curator.x.discovery.ServiceDiscovery#queryForInstances()

The following examples show how to use org.apache.curator.x.discovery.ServiceDiscovery#queryForInstances() . 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: DiscoveryExample.java    From xian with Apache License 2.0 6 votes vote down vote up
private static void listInstances(ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception
{
    // This shows how to query all the instances in group discovery

    try
    {
        Collection<String>  serviceNames = serviceDiscovery.queryForNames();
        System.out.println(serviceNames.size() + " type(s)");
        for ( String serviceName : serviceNames )
        {
            Collection<ServiceInstance<InstanceDetails>> instances = serviceDiscovery.queryForInstances(serviceName);
            System.out.println(serviceName);
            for ( ServiceInstance<InstanceDetails> instance : instances )
            {
                outputInstance(instance);
            }
        }
    }
    finally
    {
        CloseableUtils.closeQuietly(serviceDiscovery);
    }
}
 
Example 2
Source File: DiscoveryExample.java    From curator with Apache License 2.0 6 votes vote down vote up
private static void listInstances(ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception
{
    // This shows how to query all the instances in service discovery

    try
    {
        Collection<String>  serviceNames = serviceDiscovery.queryForNames();
        System.out.println(serviceNames.size() + " type(s)");
        for ( String serviceName : serviceNames )
        {
            Collection<ServiceInstance<InstanceDetails>> instances = serviceDiscovery.queryForInstances(serviceName);
            System.out.println(serviceName);
            for ( ServiceInstance<InstanceDetails> instance : instances )
            {
                outputInstance(instance);
            }
        }
    }
    finally
    {
        CloseableUtils.closeQuietly(serviceDiscovery);
    }
}
 
Example 3
Source File: DiscoveryExample.java    From ZKRecipesByExample with Apache License 2.0 6 votes vote down vote up
private static void listInstances(ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
	// This shows how to query all the instances in service discovery
	try {
		Collection<String> serviceNames = serviceDiscovery.queryForNames();
		System.out.println(serviceNames.size() + " type(s)");
		for (String serviceName : serviceNames) {
			Collection<ServiceInstance<InstanceDetails>> instances = serviceDiscovery.queryForInstances(serviceName);
			System.out.println(serviceName);
			for (ServiceInstance<InstanceDetails> instance : instances) {
				outputInstance(instance);
			}
		}
	} finally {
		CloseableUtils.closeQuietly(serviceDiscovery);
	}
}
 
Example 4
Source File: CamelCloudZookeeperServiceRegistryTest.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Test
public void testServiceRegistry() throws Exception {
    final ZookeeperServer server = new ZookeeperServer(temporaryFolder.newFolder(testName.getMethodName()));

    ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
        .web(WebApplicationType.NONE)
        .run(
            "--debug=false",
            "--spring.main.banner-mode=OFF",
            "--spring.application.name=" + UUID.randomUUID().toString(),
            "--ribbon.enabled=false",
            "--ribbon.eureka.enabled=false",
            "--management.endpoint.enabled=false",
            "--spring.cloud.zookeeper.enabled=true",
            "--spring.cloud.zookeeper.connect-string=" + server.connectString(),
            "--spring.cloud.zookeeper.config.enabled=false",
            "--spring.cloud.zookeeper.discovery.enabled=true",
            "--spring.cloud.service-registry.auto-registration.enabled=false",
            "--camel.cloud.service-registry.service-host=" + SERVICE_HOST
        );

    try {
        final ServiceDiscovery client = context.getBean(ServiceDiscovery.class);
        final ServiceRegistry registry = context.getBean(ServiceRegistry.class);

        registry.register(
            DefaultServiceDefinition.builder()
                .withHost(SERVICE_HOST)
                .withPort(SERVICE_PORT)
                .withName(SERVICE_NAME)
                .withId(SERVICE_ID)
                .build()
        );

        Collection<ServiceInstance<ZookeeperInstance>> services = client.queryForInstances(SERVICE_NAME);
        
        assertThat(services).hasSize(1);
        assertThat(services).first().hasFieldOrPropertyWithValue("address", SERVICE_HOST);
        assertThat(services).first().hasFieldOrPropertyWithValue("port", SERVICE_PORT);
        assertThat(services).first().extracting("payload").hasFieldOrPropertyWithValue("id", SERVICE_ID);
        assertThat(services).first().extracting("payload").hasFieldOrPropertyWithValue("name", SERVICE_NAME);

    } finally {
        // shutdown spring context
        context.close();

        // shutdown zookeeper
        server.shutdown();
    }
}
 
Example 5
Source File: CuratorSchedulerTest.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {

    final String zkString = zkTestServer.getConnectString();

    ServiceDiscovery<LinkedHashMap> serviceDiscovery = null;
    CuratorFramework curatorClient = null;
    try {

        final CuratorScheduler.JsonInstanceSerializer<LinkedHashMap> serializer = new CuratorScheduler.JsonInstanceSerializer<>(
                LinkedHashMap.class);
        String servicePath = CuratorScheduler.KYLIN_SERVICE_PATH;
        curatorClient = ZKUtil.newZookeeperClient(zkString, new ExponentialBackoffRetry(3000, 3));
        serviceDiscovery = ServiceDiscoveryBuilder.builder(LinkedHashMap.class).client(curatorClient)
                .basePath(servicePath).serializer(serializer).build();
        serviceDiscovery.start();

        final ExampleServer server1 = new ExampleServer("localhost:1111");
        final ExampleServer server2 = new ExampleServer("localhost:2222");

        Collection<String> serviceNames = serviceDiscovery.queryForNames();
        Assert.assertTrue(serviceNames.size() == 1);
        Assert.assertTrue(CuratorScheduler.SERVICE_NAME.equals(serviceNames.iterator().next()));
        Collection<ServiceInstance<LinkedHashMap>> instances = serviceDiscovery
                .queryForInstances(CuratorScheduler.SERVICE_NAME);
        Assert.assertTrue(instances.size() == 2);
        List<ServiceInstance<LinkedHashMap>> instancesList = Lists.newArrayList(instances);

        final List<String> instanceNodes = Lists.transform(instancesList,
                new Function<ServiceInstance<LinkedHashMap>, String>() {

                    @Nullable
                    @Override
                    public String apply(@Nullable ServiceInstance<LinkedHashMap> stringServiceInstance) {
                        return (String) stringServiceInstance.getPayload()
                                .get(CuratorScheduler.SERVICE_PAYLOAD_DESCRIPTION);
                    }
                });

        Assert.assertTrue(instanceNodes.contains(server1.getAddress() + ":query"));
        Assert.assertTrue(instanceNodes.contains(server2.getAddress() + ":query"));

        // stop one server
        server1.close();
        instances = serviceDiscovery.queryForInstances(CuratorScheduler.SERVICE_NAME);
        Assert.assertTrue(instances.size() == 1);
        Assert.assertEquals(server2.getAddress() + ":query",
                instances.iterator().next().getPayload().get(CuratorScheduler.SERVICE_PAYLOAD_DESCRIPTION));

        // all stop
        server2.close();
        instances = serviceDiscovery.queryForInstances(CuratorScheduler.SERVICE_NAME);
        Assert.assertTrue(instances.size() == 0);

    } finally {
        CloseableUtils.closeQuietly(serviceDiscovery);
        CloseableUtils.closeQuietly(curatorClient);
    }

}
 
Example 6
Source File: ConsumerClient.java    From BigData-In-Practice with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    ServiceDiscovery<InstanceDetails> serviceDiscovery;
    try (CuratorFramework client = ZKUtils.getClient()) {
        client.start();
        client.blockUntilConnected();

        serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
                .client(client)
                .basePath(InstanceDetails.ROOT_PATH)
                .serializer(new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class))
                .build();
    }
    serviceDiscovery.start();

    boolean flag = true;

    // 死循环来不停的获取服务列表,查看是否有新服务发布
    while (flag) {

        //根据名称获取服务
        Collection<ServiceInstance<InstanceDetails>> services = serviceDiscovery.queryForInstances("OrderService");
        if (services.size() == 0) {
            System.out.println("当前没有发现服务");
            Thread.sleep(10 * 1000);
            continue;
        }

        for (ServiceInstance<InstanceDetails> service : services) {

            //获取请求的scheme 例如:http://127.0.0.1:8080
            String uriSpec = service.buildUriSpec();
            //获取服务的其他信息
            InstanceDetails payload = service.getPayload();

            //服务描述
            String serviceDesc = payload.getServiceDesc();
            //获取该服务下的所有接口
            Map<String, InstanceDetails.Service> allService = payload.getServices();
            Set<Map.Entry<String, InstanceDetails.Service>> entries = allService.entrySet();

            for (Map.Entry<String, InstanceDetails.Service> entry : entries) {
                System.out.println(serviceDesc + uriSpec
                        + "/" + service.getName()
                        + "/" + entry.getKey()
                        + " 该方法需要的参数为:"
                        + entry.getValue().getParams().toString());
            }
        }
        System.out.println("---------------------");
        Thread.sleep(10 * 1000);
    }

}
 
Example 7
Source File: KylinServerDiscoveryTest.java    From kylin with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {

    final String zkString = zkTestServer.getConnectString();

    ServiceDiscovery<LinkedHashMap> serviceDiscovery = null;
    CuratorFramework curatorClient = null;
    try {
        String servicePath = KylinServerDiscovery.SERVICE_PATH;
        final KylinServerDiscovery.JsonInstanceSerializer<LinkedHashMap> serializer =
                new KylinServerDiscovery.JsonInstanceSerializer<>(LinkedHashMap.class);
        curatorClient = ZKUtil.newZookeeperClient(zkString, new ExponentialBackoffRetry(3000, 3));
        serviceDiscovery = ServiceDiscoveryBuilder.builder(LinkedHashMap.class).client(curatorClient)
                .basePath(servicePath).serializer(serializer).build();
        serviceDiscovery.start();

        final ExampleServer server1 = new ExampleServer("localhost:1111");
        final ExampleServer server2 = new ExampleServer("localhost:2222");

        Collection<String> serviceNames = serviceDiscovery.queryForNames();
        Assert.assertTrue(serviceNames.size() == 1);
        Assert.assertTrue(KylinServerDiscovery.SERVICE_NAME.equals(serviceNames.iterator().next()));
        Collection<ServiceInstance<LinkedHashMap>> instances = serviceDiscovery
                .queryForInstances(KylinServerDiscovery.SERVICE_NAME);
        Assert.assertTrue(instances.size() == 2);
        List<ServiceInstance<LinkedHashMap>> instancesList = Lists.newArrayList(instances);

        final List<String> instanceNodes = instancesList.stream()
                .map(input -> input.getAddress() + ":" + input.getPort() + ":"
                        + input.getPayload().get(KylinServerDiscovery.SERVICE_PAYLOAD_DESCRIPTION))
                .collect(Collectors.toList());

        Assert.assertTrue(instanceNodes.contains(server1.getAddress() + ":query"));
        Assert.assertTrue(instanceNodes.contains(server2.getAddress() + ":query"));

        // stop one server
        server1.close();
        instances = serviceDiscovery.queryForInstances(KylinServerDiscovery.SERVICE_NAME);
        ServiceInstance<LinkedHashMap> existingInstance = instances.iterator().next();
        Assert.assertTrue(instances.size() == 1);
        Assert.assertEquals(server2.getAddress() + ":query",
                existingInstance.getAddress() + ":" + existingInstance.getPort() + ":"
                        + existingInstance.getPayload().get(KylinServerDiscovery.SERVICE_PAYLOAD_DESCRIPTION));

        // all stop
        server2.close();
        instances = serviceDiscovery.queryForInstances(KylinServerDiscovery.SERVICE_NAME);
        Assert.assertTrue(instances.size() == 0);

    } finally {
        CloseableUtils.closeQuietly(serviceDiscovery);
        CloseableUtils.closeQuietly(curatorClient);
    }

}