org.apache.curator.x.discovery.ServiceDiscovery Java Examples

The following examples show how to use org.apache.curator.x.discovery.ServiceDiscovery. 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 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: AgentServicesAutoConfigurationTest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Verify beans in case Zookeeper is enabled.
 */
@Test
void expectedBeansExistWithZookeeperEnabled() {
    this.contextRunner
        .withUserConfiguration(ZookeeperMockConfig.class)
        .run(
            context -> {
                Assertions.assertThat(context).hasSingleBean(ServiceDiscovery.class);
                Assertions.assertThat(context).hasSingleBean(AgentJobService.class);
                Assertions.assertThat(context).hasSingleBean(AgentConnectionTrackingService.class);
                Assertions.assertThat(context).hasSingleBean(AgentRoutingService.class);
                Assertions.assertThat(context).hasSingleBean(AgentFilterService.class);
                Assertions.assertThat(context).hasSingleBean(AgentConfigurationProperties.class);
                Assertions.assertThat(context).hasSingleBean(AgentConfigurationService.class);
            }
        );
}
 
Example #8
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 #9
Source File: AgentRoutingServiceCuratorDiscoveryImpl.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param genieHostInfo                    The genie local host information
 * @param serviceDiscovery                 The service discovery client
 * @param taskScheduler                    The task scheduler
 * @param listenableCuratorConnectionState The listenable curator client connection status
 * @param registry                         The metrics registry
 */
public AgentRoutingServiceCuratorDiscoveryImpl(
    final GenieHostInfo genieHostInfo,
    final ServiceDiscovery<Agent> serviceDiscovery,
    final TaskScheduler taskScheduler,
    final Listenable<ConnectionStateListener> listenableCuratorConnectionState,
    final MeterRegistry registry
) {
    this.localHostname = genieHostInfo.getHostname();
    this.serviceDiscovery = serviceDiscovery;
    this.taskScheduler = taskScheduler;
    this.registry = registry;

    // Schedule periodic reconciliation between in-memory connected set and Service Discovery state
    this.taskScheduler.schedule(this::reconcileRegistrationsTask, trigger);

    // Listen for Curator session state changes
    listenableCuratorConnectionState.addListener(this::handleConnectionStateChange);

    // Create gauge metric for agents connected and registered
    registry.gauge(CONNECTED_AGENTS_GAUGE_NAME, EMPTY_TAG_SET, this.connectedAgentsSet, Set::size);
    registry.gaugeMapSize(REGISTERED_AGENTS_GAUGE_NAME, EMPTY_TAG_SET, this.registeredAgentsMap);
}
 
Example #10
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 #11
Source File: ZookeeperBridgeTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Before
public void startZookeeper() throws Exception {
  zkTestServer = new TestingServer(2181);
  cli = CuratorFrameworkFactory.newClient(zkTestServer.getConnectString(), new RetryOneTime(2000));
  cli.start();

  discovery = ServiceDiscoveryBuilder.builder(String.class)
    .client(cli)
    .basePath("/discovery")
    .watchInstances(true)
    .build();

  discovery.start();
  vertx = Vertx.vertx();
  sd = io.vertx.servicediscovery.ServiceDiscovery.create(vertx);
}
 
Example #12
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 #13
Source File: AgentServicesAutoConfiguration.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Get an implementation of {@link AgentRoutingService} if one hasn't already been defined.
 * This bean is created if Zookeeper is enabled, it uses Curator's {@link ServiceDiscovery}.
 *
 * @param genieHostInfo                    The local genie host information
 * @param serviceDiscovery                 The Zookeeper Curator service discovery
 * @param taskScheduler                    The task scheduler
 * @param listenableCuratorConnectionState the connection state listenable
 * @param registry                         The metrics registry
 * @return A {@link AgentRoutingServiceImpl} instance
 */
@Bean
@ConditionalOnBean(ServiceDiscovery.class)
@ConditionalOnMissingBean(AgentRoutingService.class)
public AgentRoutingService agentRoutingServiceCurator(
    final GenieHostInfo genieHostInfo,
    final ServiceDiscovery<AgentRoutingServiceCuratorDiscoveryImpl.Agent> serviceDiscovery,
    @Qualifier("genieTaskScheduler") final TaskScheduler taskScheduler,
    final Listenable<ConnectionStateListener> listenableCuratorConnectionState,
    final MeterRegistry registry
) {
    return new AgentRoutingServiceCuratorDiscoveryImpl(
        genieHostInfo,
        serviceDiscovery,
        taskScheduler,
        listenableCuratorConnectionState,
        registry
    );
}
 
Example #14
Source File: DiscoveryClient.java    From snowizard-discovery with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Constructor
 *
 * @param serviceName
 *            name of the service to monitor
 * @param discovery
 *            {@link ServiceDiscovery}
 * @param downInstancePolicy
 *            {@link DownInstancePolicy} to use when marking instances as
 *            down
 * @param providerStrategy
 *            {@link ProviderStrategy} to use when selecting an instance
 */
public DiscoveryClient(final String serviceName,
        final ServiceDiscovery<InstanceMetadata> discovery,
        final DownInstancePolicy downInstancePolicy,
        final ProviderStrategy<InstanceMetadata> providerStrategy) {
    checkNotNull(serviceName);
    checkArgument(!serviceName.isEmpty(), "serviceName cannot be empty");
    checkNotNull(providerStrategy);

    this.discovery = checkNotNull(discovery);

    this.provider = discovery.serviceProviderBuilder()
            .serviceName(serviceName)
            .downInstancePolicy(downInstancePolicy)
            .providerStrategy(providerStrategy).build();
}
 
Example #15
Source File: TestServiceDiscovery.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic() 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();

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

        List<ServiceInstance<String>> list = Lists.newArrayList();
        list.add(instance);
        Assert.assertEquals(discovery.queryForInstances("test"), list);
    }
    finally
    {
        CloseableUtils.closeQuietly(discovery);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #16
Source File: DiscoveryExample.java    From ZKRecipesByExample with Apache License 2.0 6 votes vote down vote up
private static void listRandomInstance(String[] args, ServiceDiscovery<InstanceDetails> serviceDiscovery,
		Map<String, ServiceProvider<InstanceDetails>> providers, String command) throws Exception {
	// this shows how to use a ServiceProvider
	// in a real application you'd create the ServiceProvider early for the
	// service(s) you're interested in
	if (args.length != 1) {
		System.err.println("syntax error (expected random <name>): " + command);
		return;
	}
	String serviceName = args[0];
	ServiceProvider<InstanceDetails> provider = providers.get(serviceName);
	if (provider == null) {
		provider = serviceDiscovery.serviceProviderBuilder().serviceName(serviceName).providerStrategy(new RandomStrategy<InstanceDetails>()).build();
		providers.put(serviceName, provider);
		provider.start();
		Thread.sleep(2500); // give the provider time to warm up - in a real
							// application you wouldn't need to do this
	}
	ServiceInstance<InstanceDetails> instance = provider.getInstance();
	if (instance == null) {
		System.err.println("No instances named: " + serviceName);
	} else {
		outputInstance(instance);
	}
}
 
Example #17
Source File: AgentServicesAutoConfigurationTest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Verify beans in case Zookeeper is not enabled.
 */
@Test
void expectedBeansExistWithZookeeperDisabled() {
    this.contextRunner
        .run(
            context -> {
                Assertions.assertThat(context).doesNotHaveBean(ServiceDiscovery.class);
                Assertions.assertThat(context).hasSingleBean(AgentRoutingService.class);
                Assertions.assertThat(context).hasSingleBean(AgentJobService.class);
                Assertions.assertThat(context).hasSingleBean(AgentConnectionTrackingService.class);
                Assertions.assertThat(context).hasSingleBean(AgentFilterService.class);
                Assertions.assertThat(context).hasSingleBean(AgentConfigurationProperties.class);
                Assertions.assertThat(context).hasSingleBean(AgentConfigurationService.class);
            }
        );
}
 
Example #18
Source File: ZookeeperServiceInstances.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
public ZookeeperServiceInstances(CuratorFramework curator,
		ServiceDiscovery<ZookeeperInstance> serviceDiscovery,
		ZookeeperDependencies zookeeperDependencies,
		ZookeeperDiscoveryProperties zookeeperDiscoveryProperties) {
	this.curator = curator;
	this.serviceDiscovery = serviceDiscovery;
	this.zookeeperDependencies = zookeeperDependencies;
	this.zookeeperDiscoveryProperties = zookeeperDiscoveryProperties;
	this.allInstances = getZookeeperInstances();
}
 
Example #19
Source File: CuratorServiceDiscoveryAutoConfiguration.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public ServiceDiscovery<ZookeeperInstance> curatorServiceDiscovery(
		ServiceDiscoveryCustomizer customizer) {
	return customizer
			.customize(ServiceDiscoveryBuilder.builder(ZookeeperInstance.class));
}
 
Example #20
Source File: DefaultServiceDiscoveryCustomizer.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceDiscovery<ZookeeperInstance> customize(
		ServiceDiscoveryBuilder<ZookeeperInstance> builder) {
	// @formatter:off
	return builder
			.client(this.curator)
			.basePath(this.properties.getRoot())
			.serializer(this.instanceSerializer)
			.build();
	// @formatter:on
}
 
Example #21
Source File: AgentServicesAutoConfiguration.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Get an implementation of {@link AgentRoutingService} if one hasn't already been defined.
 * This bean is created if Zookeeper is disabled. This implementation stores connections using persistence service.
 *
 * @param persistenceService The persistence service to use for agent connections
 * @param genieHostInfo      The local genie host information
 * @return A {@link AgentRoutingServiceImpl} instance
 */
@Bean
@ConditionalOnMissingBean(
    {
        AgentRoutingService.class,
        ServiceDiscovery.class
    }
)
public AgentRoutingService agentRoutingServicePersistence(
    final PersistenceService persistenceService,
    final GenieHostInfo genieHostInfo
) {
    return new AgentRoutingServiceImpl(persistenceService, genieHostInfo);
}
 
Example #22
Source File: ZookeeperDiscoveryClientTests.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Test
public void getServicesShouldReturnEmptyWhenNoNodeException() throws Exception {
	// given:
	ServiceDiscovery<ZookeeperInstance> serviceDiscovery = mock(
			ServiceDiscovery.class);
	when(serviceDiscovery.queryForNames()).thenThrow(new NoNodeException());
	ZookeeperDiscoveryClient discoveryClient = new ZookeeperDiscoveryClient(
			serviceDiscovery, null, new ZookeeperDiscoveryProperties());
	// when:
	List<String> services = discoveryClient.getServices();
	// then:
	then(services).isEmpty();
}
 
Example #23
Source File: ZookeeperDiscoveryClientTests.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Test
public void getInstancesshouldReturnEmptyWhenNoNodeException() throws Exception {
	// given:
	ServiceDiscovery<ZookeeperInstance> serviceDiscovery = mock(
			ServiceDiscovery.class);
	when(serviceDiscovery.queryForInstances("myservice"))
			.thenThrow(new NoNodeException());
	ZookeeperDiscoveryClient discoveryClient = new ZookeeperDiscoveryClient(
			serviceDiscovery, null, new ZookeeperDiscoveryProperties());
	// when:
	List<ServiceInstance> instances = discoveryClient.getInstances("myservice");
	// then:
	then(instances).isEmpty();
}
 
Example #24
Source File: DependencyWatcherAutoConfiguration.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Bean(destroyMethod = "clearDependencyRegistrationHooks")
@ConditionalOnMissingBean
public DependencyRegistrationHookProvider dependencyWatcher(
		ServiceDiscovery<ZookeeperInstance> serviceDiscovery,
		DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier,
		ZookeeperDependencies zookeeperDependencies) {
	return new DefaultDependencyWatcher(serviceDiscovery,
			dependencyPresenceOnStartupVerifier, this.dependencyWatcherListeners,
			zookeeperDependencies);
}
 
Example #25
Source File: DefaultDependencyWatcher.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
public DefaultDependencyWatcher(ServiceDiscovery<ZookeeperInstance> serviceDiscovery,
		DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier,
		List<DependencyWatcherListener> dependencyWatcherListeners,
		ZookeeperDependencies zookeeperDependencies) {
	this.serviceDiscovery = serviceDiscovery;
	this.dependencyPresenceOnStartupVerifier = dependencyPresenceOnStartupVerifier;
	this.listeners = dependencyWatcherListeners;
	this.zookeeperDependencies = zookeeperDependencies;
}
 
Example #26
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 #27
Source File: ITClusterModuleZookeeperProviderFunctionalTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void unregisterRemoteOfCluster() throws Exception {
    final String namespace = "unregister_remote_cluster";
    ModuleProvider providerA = createProvider(namespace);
    ModuleProvider providerB = createProvider(namespace);

    Address addressA = new Address("127.0.0.4", 1000, true);
    Address addressB = new Address("127.0.0.5", 1000, true);

    RemoteInstance instanceA = new RemoteInstance(addressA);
    RemoteInstance instanceB = new RemoteInstance(addressB);

    getClusterRegister(providerA).registerRemote(instanceA);
    getClusterRegister(providerB).registerRemote(instanceB);

    List<RemoteInstance> remoteInstancesOfA = queryRemoteNodes(providerA, 2);
    validateServiceInstance(addressA, addressB, remoteInstancesOfA);

    List<RemoteInstance> remoteInstancesOfB = queryRemoteNodes(providerB, 2);
    validateServiceInstance(addressB, addressA, remoteInstancesOfB);

    // unregister A
    ClusterRegister register = getClusterRegister(providerA);
    ServiceDiscovery<RemoteInstance> discoveryA = Whitebox.getInternalState(register, "serviceDiscovery");
    discoveryA.close();

    // only B
    remoteInstancesOfB = queryRemoteNodes(providerB, 1, 120);
    assertEquals(1, remoteInstancesOfB.size());
    Address address = remoteInstancesOfB.get(0).getAddress();
    assertEquals(address, addressB);
    assertTrue(addressB.isSelf());
}
 
Example #28
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 #29
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private ServiceDiscovery<byte[]> getDiscovery(CuratorFramework curatorFramework)
{
  return ServiceDiscoveryBuilder.builder(byte[].class)
          .basePath(basePath)
          .client(curatorFramework)
          .serializer(instanceSerializerFactory.getInstanceSerializer(
          new TypeReference<ServiceInstance<byte[]>>()
            {})).build();
}
 
Example #30
Source File: ZKClusterCoordinator.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected ServiceDiscovery<DrillbitEndpoint> newDiscovery() {
  return ServiceDiscoveryBuilder
    .builder(DrillbitEndpoint.class)
    .basePath("/")
    .client(curator)
    .serializer(DrillServiceInstanceHelper.SERIALIZER)
    .build();
}