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

The following examples show how to use org.apache.curator.x.discovery.ServiceDiscovery#start() . 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: RemoteServiceLocatorConfig.java    From springboot-plus with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void addServiceURI(String path, String url) {
	try{
		ServiceInstanceBuilder<Map> service = ServiceInstance.builder();
		service.address("");
		service.port(0);
		service.name(path);
		Map config = new HashMap();
		config.put("url", url);
		service.payload(config);

		ServiceInstance<Map> instance = service.build();

		ServiceDiscovery<Map> serviceDiscovery = ServiceDiscoveryBuilder.builder(Map.class).client(client)
				.serializer(new JsonInstanceSerializer<Map>(Map.class)).basePath("/service").build();
		// 服务注册
		serviceDiscovery.registerService(instance);
		serviceDiscovery.start();
	}catch(Exception ex){
		log.warn(ex.getMessage(), ex);
		throw new PlatformException("服务注册中心 出错",ex);
	}
	
	
}
 
Example 2
Source File: TestServiceDiscovery.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCleaning() throws Exception
{
    CuratorFramework client = null;
    ServiceDiscovery<String> discovery = null;
    try
    {
        client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
        discovery.start();
        discovery.unregisterService(instance);

        Assert.assertEquals(((ServiceDiscoveryImpl)discovery).debugServicesQty(), 0);
    }
    finally
    {
        CloseableUtils.closeQuietly(discovery);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 3
Source File: DiscoveryExample.java    From ZKRecipesByExample with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	// This method is scaffolding to get the example up and running
	TestingServer server = new TestingServer();
	CuratorFramework client = null;
	ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
	Map<String, ServiceProvider<InstanceDetails>> providers = Maps.newHashMap();
	try {
		client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
		client.start();
		JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);
		serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH).serializer(serializer).build();
		serviceDiscovery.start();
		processCommands(serviceDiscovery, providers, client);
	} finally {
		for (ServiceProvider<InstanceDetails> cache : providers.values()) {
			CloseableUtils.closeQuietly(cache);
		}
		CloseableUtils.closeQuietly(serviceDiscovery);
		CloseableUtils.closeQuietly(client);
		CloseableUtils.closeQuietly(server);
	}
}
 
Example 4
Source File: ZookeeperStubsRegistrar.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Override
public void registerStubs() {
	Map<StubConfiguration, Integer> activeStubs = this.stubRunning.runStubs()
			.validNamesAndPorts();
	for (Map.Entry<StubConfiguration, Integer> entry : activeStubs.entrySet()) {
		ServiceInstance serviceInstance = serviceInstance(entry.getKey(),
				entry.getValue());
		ServiceDiscovery serviceDiscovery = serviceDiscovery(serviceInstance);
		this.discoveryList.add(serviceDiscovery);
		try {
			serviceDiscovery.start();
			if (log.isDebugEnabled()) {
				log.debug("Successfully registered stub ["
						+ entry.getKey().toColonSeparatedDependencyNotation()
						+ "] in Service Discovery");
			}
		}
		catch (Exception e) {
			log.warn("Exception occurred while trying to register a stub ["
					+ entry.getKey().toColonSeparatedDependencyNotation()
					+ "] in Service Discovery", e);
		}
	}
}
 
Example 5
Source File: ZookeeperServiceDiscovery.java    From Microservices-Deployment-Cookbook with MIT License 6 votes vote down vote up
private static ServiceProvider<Object> getGeolocationServiceProvider() throws Exception {
	if(geolocationServiceProvider == null) {
		CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("192.168.99.100:2181", new RetryNTimes(5, 1000));
		curatorFramework.start();

		ServiceDiscovery<Object> serviceDiscovery = ServiceDiscoveryBuilder.builder(Object.class)
				.basePath("com.packt.microservices")
				.client(curatorFramework)
				.build();
		serviceDiscovery.start();

		geolocationServiceProvider = serviceDiscovery.serviceProviderBuilder()
				.serviceName("geolocation")
				.build();
		geolocationServiceProvider.start();
	}
	return geolocationServiceProvider;
}
 
Example 6
Source File: MetaServerBaseTest.java    From hermes with Apache License 2.0 6 votes vote down vote up
private int brokerRegisterToZK() throws Exception {
	int port = brokerPort.getAndIncrement();
	ServiceInstance<Void> thisInstance = ServiceInstance.<Void> builder()//
	      .name("default")//
	      .address(localhostIP)//
	      .port(port)//
	      .id(String.valueOf(port))//
	      .build();

	ServiceDiscovery<Void> m_serviceDiscovery = ServiceDiscoveryBuilder.builder(Void.class)//
	      .client(m_client.get())//
	      .basePath("brokers")//
	      .thisInstance(thisInstance)//
	      .build();
	m_serviceDiscovery.start();

	if (tempBrokers.containsKey(port)) {
		throw new RuntimeException("Already Existed in tempBrokers!!");
	} else {
		tempBrokers.put(port, m_serviceDiscovery);
		return port;
	}
}
 
Example 7
Source File: TestServiceProvider.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        ServiceProvider<String> provider = discovery.serviceProviderBuilder().serviceName("test").build();
        closeables.add(provider);
        provider.start();

        Assert.assertEquals(provider.getInstance(), instance);

        List<ServiceInstance<String>> list = Lists.newArrayList();
        list.add(instance);
        Assert.assertEquals(provider.getAllInstances(), list);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 8
Source File: TestServiceDiscovery.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testCleaning() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();
        discovery.unregisterService(instance);

        Assert.assertEquals(((ServiceDiscoveryImpl)discovery).debugServicesQty(), 0);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 9
Source File: TestServiceDiscovery.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        Assert.assertEquals(discovery.queryForNames(), Collections.singletonList("test"));

        List<ServiceInstance<String>> list = Lists.newArrayList();
        list.add(instance);
        Assert.assertEquals(discovery.queryForInstances("test"), list);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 10
Source File: TestServiceDiscovery.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testCrashedInstance() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        Timing timing = new Timing();

        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceDiscovery<String> discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class), new FastjsonServiceDefinitionSerializer<>(String.class), instance, false);
        closeables.add(discovery);
        discovery.start();

        Assert.assertEquals(discovery.queryForInstances("test").size(), 1);

        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
        Thread.sleep(timing.multiple(1.5).session());

        Assert.assertEquals(discovery.queryForInstances("test").size(), 1);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 11
Source File: TestServiceDiscovery.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCrashedInstance() throws Exception
{
    CuratorFramework client = null;
    ServiceDiscovery<String> discovery = null;
    try
    {
        Timing timing = new Timing();

        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class), instance, false);
        discovery.start();

        Assert.assertEquals(discovery.queryForInstances("test").size(), 1);

        client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
        Thread.sleep(timing.multiple(1.5).session());

        Assert.assertEquals(discovery.queryForInstances("test").size(), 1);
    }
    finally
    {
        CloseableUtils.closeQuietly(discovery);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 12
Source File: TestServiceProvider.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisabledInstance() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).enabled(false).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        ServiceProvider<String> provider = discovery.serviceProviderBuilder().serviceName("test").build();
        closeables.add(provider);
        provider.start();

        Assert.assertEquals(provider.getInstance(), null);
        Assert.assertTrue(provider.getAllInstances().isEmpty(), "Disabled instance still appears available via group provider");
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 13
Source File: TestServiceProvider.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        ServiceProvider<String> provider = discovery.serviceProviderBuilder().serviceName("test").build();
        closeables.add(provider);
        provider.start();

        Assert.assertEquals(provider.getInstance(), instance);

        List<ServiceInstance<String>> list = Lists.newArrayList();
        list.add(instance);
        Assert.assertEquals(provider.getAllInstances(), list);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 14
Source File: TestServiceProvider.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisabledInstance() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).enabled(false).build();
        InstanceSerializer<String> serializer = new JsonInstanceSerializer<>(String.class, false);
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).serializer(serializer).basePath("/test").client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        ServiceProvider<String> provider = discovery.serviceProviderBuilder().serviceName("test").build();
        closeables.add(provider);
        provider.start();

        Assert.assertEquals(provider.getInstance(), null);
        Assert.assertTrue(provider.getAllInstances().isEmpty(), "Disabled instance still appears available via service provider");
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 15
Source File: TestServiceDiscovery.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipleInstances() throws Exception
{
    final String SERVICE_ONE = "one";
    final String SERVICE_TWO = "two";

    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<Void> s1_i1 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
        ServiceInstance<Void> s1_i2 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
        ServiceInstance<Void> s2_i1 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();
        ServiceInstance<Void> s2_i2 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();

        ServiceDiscovery<Void> discovery = ServiceDiscoveryBuilder.builder(Void.class).client(client).basePath("/test").build();
        closeables.add(discovery);
        discovery.start();

        discovery.registerService(s1_i1);
        discovery.registerService(s1_i2);
        discovery.registerService(s2_i1);
        discovery.registerService(s2_i2);

        Assert.assertEquals(Sets.newHashSet(discovery.queryForNames()), Sets.newHashSet(SERVICE_ONE, SERVICE_TWO));

        List<ServiceInstance<Void>> list = Lists.newArrayList();
        list.add(s1_i1);
        list.add(s1_i2);
        Collections.sort(list, comparator);
        List<ServiceInstance<Void>> queriedInstances = Lists.newArrayList(discovery.queryForInstances(SERVICE_ONE));
        Collections.sort(queriedInstances, comparator);
        Assert.assertEquals(queriedInstances, list, String.format("Not equal l: %s - d: %s", list, queriedInstances));

        list.clear();

        list.add(s2_i1);
        list.add(s2_i2);
        Collections.sort(list, comparator);
        queriedInstances = Lists.newArrayList(discovery.queryForInstances(SERVICE_TWO));
        Collections.sort(queriedInstances, comparator);
        Assert.assertEquals(queriedInstances, list, String.format("Not equal 2: %s - d: %s", list, queriedInstances));
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 16
Source File: TestServiceDiscovery.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrashedServerMultiInstances() throws Exception
{
    CuratorFramework client = null;
    ServiceDiscovery<String> discovery = null;
    try
    {
        Timing timing = new Timing();
        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        client.start();

        final Semaphore semaphore = new Semaphore(0);
        ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("thing").name("test").port(10065).build();
        discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class), instance1, false)
        {
            @Override
            protected void internalRegisterService(ServiceInstance<String> service) throws Exception
            {
                super.internalRegisterService(service);
                semaphore.release();
            }
        };
        discovery.start();
        discovery.registerService(instance2);

        timing.acquireSemaphore(semaphore, 2);
        Assert.assertEquals(discovery.queryForInstances("test").size(), 2);

        client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
        server.stop();

        server.restart();

        timing.acquireSemaphore(semaphore, 2);
        Assert.assertEquals(discovery.queryForInstances("test").size(), 2);
    }
    finally
    {
        CloseableUtils.closeQuietly(discovery);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 17
Source File: TestServiceDiscovery.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipleInstances() throws Exception
{
    final String SERVICE_ONE = "one";
    final String SERVICE_TWO = "two";

    CuratorFramework client = null;
    ServiceDiscovery<Void> discovery = null;
    try
    {
        client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client.start();

        ServiceInstance<Void> s1_i1 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
        ServiceInstance<Void> s1_i2 = ServiceInstance.<Void>builder().name(SERVICE_ONE).build();
        ServiceInstance<Void> s2_i1 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();
        ServiceInstance<Void> s2_i2 = ServiceInstance.<Void>builder().name(SERVICE_TWO).build();

        discovery = ServiceDiscoveryBuilder.builder(Void.class).client(client).basePath("/test").build();
        discovery.start();

        discovery.registerService(s1_i1);
        discovery.registerService(s1_i2);
        discovery.registerService(s2_i1);
        discovery.registerService(s2_i2);

        Assert.assertEquals(Sets.newHashSet(discovery.queryForNames()), Sets.newHashSet(SERVICE_ONE, SERVICE_TWO));

        List<ServiceInstance<Void>> list = Lists.newArrayList();
        list.add(s1_i1);
        list.add(s1_i2);
        Collections.sort(list, comparator);
        List<ServiceInstance<Void>> queriedInstances = Lists.newArrayList(discovery.queryForInstances(SERVICE_ONE));
        Collections.sort(queriedInstances, comparator);
        Assert.assertEquals(queriedInstances, list, String.format("Not equal l: %s - d: %s", list, queriedInstances));

        list.clear();

        list.add(s2_i1);
        list.add(s2_i2);
        Collections.sort(list, comparator);
        queriedInstances = Lists.newArrayList(discovery.queryForInstances(SERVICE_TWO));
        Collections.sort(queriedInstances, comparator);
        Assert.assertEquals(queriedInstances, list, String.format("Not equal 2: %s - d: %s", list, queriedInstances));
    }
    finally
    {
        CloseableUtils.closeQuietly(discovery);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 18
Source File: TestServiceDiscovery.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrashedServerMultiInstances() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        Timing timing = new Timing();
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        final Semaphore semaphore = new Semaphore(0);
        ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("thing").name("test").port(10065).build();
        ServiceDiscovery<String> discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class),new FastjsonServiceDefinitionSerializer<>(String.class), instance1, false)
        {
            @Override
            protected void internalRegisterService(ServiceInstance<String> service) throws Exception
            {
                super.internalRegisterService(service);
                semaphore.release();
            }
        };
        closeables.add(discovery);
        discovery.start();
        discovery.registerService(instance2);

        timing.acquireSemaphore(semaphore, 2);
        Assert.assertEquals(discovery.queryForInstances("test").size(), 2);

        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
        server.stop();

        server.restart();
        closeables.add(server);

        timing.acquireSemaphore(semaphore, 2);
        Assert.assertEquals(discovery.queryForInstances("test").size(), 2);
    }
    finally
    {
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 19
Source File: TestServiceDiscovery.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrashedServer() throws Exception
{
    CuratorFramework client = null;
    ServiceDiscovery<String> discovery = null;
    try
    {
        Timing timing = new Timing();
        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        client.start();

        final Semaphore semaphore = new Semaphore(0);
        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class), instance, false)
        {
            @Override
            protected void internalRegisterService(ServiceInstance<String> service) throws Exception
            {
                super.internalRegisterService(service);
                semaphore.release();
            }
        };
        discovery.start();

        timing.acquireSemaphore(semaphore);
        Assert.assertEquals(discovery.queryForInstances("test").size(), 1);

        client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
        server.stop();

        server.restart();

        timing.acquireSemaphore(semaphore);
        Assert.assertEquals(discovery.queryForInstances("test").size(), 1);
    }
    finally
    {
        CloseableUtils.closeQuietly(discovery);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 20
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);
    }

}