org.apache.curator.x.discovery.details.JsonInstanceSerializer Java Examples

The following examples show how to use org.apache.curator.x.discovery.details.JsonInstanceSerializer. 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: 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 #3
Source File: TestJsonInstanceSerializer.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void		testPayloadClass() throws Exception
{
    JsonInstanceSerializer<Payload>    serializer = new JsonInstanceSerializer<Payload>(Payload.class);
    Payload payload = new Payload();
    payload.setVal("Test value");
    ServiceInstance<Payload>           instance = new ServiceInstance<Payload>("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true);
    byte[]                             bytes = serializer.serialize(instance);

    ServiceInstance<Payload>           rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #4
Source File: TestJsonInstanceSerializer.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void		testPayloadAsMap() throws Exception
{
    JsonInstanceSerializer<Object>    serializer = new JsonInstanceSerializer<Object>(Object.class, false);
    Map<String,String> payload = new HashMap<String,String>();
    payload.put("1", "Test value 1");
    payload.put("2", "Test value 2");
    ServiceInstance<Object>           instance = new ServiceInstance<Object>("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false);
    byte[]                            bytes = serializer.serialize(instance);

    ServiceInstance<Object>           rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #5
Source File: TestJsonInstanceSerializer.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void		testPayloadAsList() throws Exception
{
    JsonInstanceSerializer<Object>    serializer = new JsonInstanceSerializer<Object>(Object.class, false);
    List<String> payload = new ArrayList<String>();
    payload.add("Test value 1");
    payload.add("Test value 2");
    ServiceInstance<Object>           instance = new ServiceInstance<Object>("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false);
    byte[]                            bytes = serializer.serialize(instance);

    ServiceInstance<Object>           rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #6
Source File: TestJsonInstanceSerializer.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void     testNoPayload() throws Exception
{
    JsonInstanceSerializer<Void>    serializer = new JsonInstanceSerializer<Void>(Void.class);
    ServiceInstance<Void>           instance = new ServiceInstance<Void>("name", "id", "address", 10, 20, null, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true);
    byte[]                          bytes = serializer.serialize(instance);

    ServiceInstance<Void>           rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #7
Source File: TestJsonInstanceSerializer.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void     testWrongPayloadType() throws Exception
{
    JsonInstanceSerializer<String>  stringSerializer = new JsonInstanceSerializer<String>(String.class);
    JsonInstanceSerializer<Double>  doubleSerializer = new JsonInstanceSerializer<Double>(Double.class);

    byte[]                          bytes = stringSerializer.serialize(new ServiceInstance<String>("name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true));
    try
    {
        doubleSerializer.deserialize(bytes);
        Assert.fail();
    }
    catch ( ClassCastException e )
    {
        // correct
    }
}
 
Example #8
Source File: TestJsonInstanceSerializer.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void     testBasic() throws Exception
{
    JsonInstanceSerializer<String>  serializer = new JsonInstanceSerializer<String>(String.class);
    ServiceInstance<String>         instance = new ServiceInstance<String>("name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true);
    byte[]                          bytes = serializer.serialize(instance);

    ServiceInstance<String>         rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #9
Source File: ExampleServer.java    From curator with Apache License 2.0 6 votes vote down vote up
public ExampleServer(CuratorFramework client, String path, String serviceName, String description) throws Exception
{
    // in a real application, you'd have a convention of some kind for the URI layout
    UriSpec     uriSpec = new UriSpec("{scheme}://foo.com:{port}");

    thisInstance = ServiceInstance.<InstanceDetails>builder()
        .name(serviceName)
        .payload(new InstanceDetails(description))
        .port((int)(65535 * Math.random())) // in a real application, you'd use a common port
        .uriSpec(uriSpec)
        .build();

    // if you mark your payload class with @JsonRootName the provided JsonInstanceSerializer will work
    JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);

    serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
        .client(client)
        .basePath(path)
        .serializer(serializer)
        .thisInstance(thisInstance)
        .build();
}
 
Example #10
Source File: TestJsonInstanceSerializer.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void		testPayloadClass() throws Exception
{
    JsonInstanceSerializer<Payload>    serializer = new JsonInstanceSerializer<Payload>(Payload.class);
    Payload payload = new Payload();
    payload.setVal("Test value");
    ServiceInstance<Payload>           instance = new ServiceInstance<Payload>("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true);
    byte[]                             bytes = serializer.serialize(instance);

    ServiceInstance<Payload>           rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #11
Source File: TestJsonInstanceSerializer.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void		testPayloadAsMap() throws Exception
{
    JsonInstanceSerializer<Object>    serializer = new JsonInstanceSerializer<Object>(Object.class);
    Map<String,String> payload = new HashMap<String,String>();
    payload.put("1", "Test value 1");
    payload.put("2", "Test value 2");
    ServiceInstance<Object>           instance = new ServiceInstance<Object>("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false);
    byte[]                            bytes = serializer.serialize(instance);

    ServiceInstance<Object>           rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #12
Source File: TestJsonInstanceSerializer.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void     testNoPayload() throws Exception
{
    JsonInstanceSerializer<Void>    serializer = new JsonInstanceSerializer<Void>(Void.class);
    ServiceInstance<Void>           instance = new ServiceInstance<Void>("name", "id", "address", 10, 20, null, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true);
    byte[]                          bytes = serializer.serialize(instance);

    ServiceInstance<Void>           rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #13
Source File: ExampleServer.java    From xian with Apache License 2.0 6 votes vote down vote up
public ExampleServer(CuratorFramework client, String path, String serviceName, String description) throws Exception
{
    // in a real application, you'd have a convention of some kind for the URI layout
    UriSpec     uriSpec = new UriSpec("{scheme}://foo.com:{port}");

    thisInstance = ServiceInstance.<InstanceDetails>builder()
        .name(serviceName)
        .payload(new InstanceDetails(description))
        .port((int)(65535 * Math.random())) // in a real application, you'd use a common port
        .uriSpec(uriSpec)
        .build();

    // if you mark your payload class with @JsonRootName the provided JsonInstanceSerializer will work
    JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);

    serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
        .client(client)
        .basePath(path)
        .serializer(serializer)
        .thisInstance(thisInstance)
        .build();
}
 
Example #14
Source File: TestJsonInstanceSerializer.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void     testBasic() throws Exception
{
    JsonInstanceSerializer<String>  serializer = new JsonInstanceSerializer<String>(String.class);
    ServiceInstance<String>         instance = new ServiceInstance<String>("name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true);
    byte[]                          bytes = serializer.serialize(instance);

    ServiceInstance<String>         rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #15
Source File: TestJsonInstanceSerializer.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void     testWrongPayloadType() throws Exception
{
    JsonInstanceSerializer<String>  stringSerializer = new JsonInstanceSerializer<String>(String.class);
    JsonInstanceSerializer<Double>  doubleSerializer = new JsonInstanceSerializer<Double>(Double.class);

    byte[]                          bytes = stringSerializer.serialize(new ServiceInstance<String>("name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true));
    try
    {
        doubleSerializer.deserialize(bytes);
        Assert.fail();
    }
    catch ( ClassCastException e )
    {
        // correct
    }
}
 
Example #16
Source File: TestJsonInstanceSerializer.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void		testPayloadAsList() throws Exception
{
    JsonInstanceSerializer<Object>    serializer = new JsonInstanceSerializer<Object>(Object.class);
    List<String> payload = new ArrayList<String>();
    payload.add("Test value 1");
    payload.add("Test value 2");
    ServiceInstance<Object>           instance = new ServiceInstance<Object>("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false);
    byte[]                            bytes = serializer.serialize(instance);

    ServiceInstance<Object>           rhs = serializer.deserialize(bytes);
    Assert.assertEquals(instance, rhs);
    Assert.assertEquals(instance.getId(), rhs.getId());
    Assert.assertEquals(instance.getName(), rhs.getName());
    Assert.assertEquals(instance.getPayload(), rhs.getPayload());
    Assert.assertEquals(instance.getAddress(), rhs.getAddress());
    Assert.assertEquals(instance.getPort(), rhs.getPort());
    Assert.assertEquals(instance.getSslPort(), rhs.getSslPort());
    Assert.assertEquals(instance.getUriSpec(), rhs.getUriSpec());
    Assert.assertEquals(instance.isEnabled(), rhs.isEnabled());
}
 
Example #17
Source File: DiscoveryExample.java    From curator with Apache License 2.0 5 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 #18
Source File: ZooKeeperServiceRegistryTest.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
public ZooKeeperTestClient(String nodes) {
    curator = CuratorFrameworkFactory.builder()
        .connectString(nodes)
        .retryPolicy(new ExponentialBackoffRetry(1000, 3))
        .build();
    discovery = ServiceDiscoveryBuilder.builder(ZooKeeperServiceRegistry.MetaData.class)
        .client(curator)
        .basePath(SERVICE_PATH)
        .serializer(new JsonInstanceSerializer<>(ZooKeeperServiceRegistry.MetaData.class))
        .build();
}
 
Example #19
Source File: ExampleServer.java    From ZKRecipesByExample with Apache License 2.0 5 votes vote down vote up
public ExampleServer(CuratorFramework client, String path, String serviceName, String description) throws Exception {
	// in a real application, you'd have a convention of some kind for the
	// URI layout
	UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}");
	thisInstance = ServiceInstance.<InstanceDetails> builder().name(serviceName).payload(new InstanceDetails(description))
			.port((int) (65535 * Math.random())) // in a real application,
													// you'd use a common
													// port
			.uriSpec(uriSpec).build();
	// if you mark your payload class with @JsonRootName the provided
	// JsonInstanceSerializer will work
	JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);
	serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(path).serializer(serializer)
			.thisInstance(thisInstance).build();
}
 
Example #20
Source File: TestJsonInstanceSerializer.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void     testNoEnabledState() throws Exception
{
    JsonInstanceSerializer<Void>    serializer = new JsonInstanceSerializer<Void>(Void.class);
    byte[]                          bytes = "{}".getBytes("utf-8");

    ServiceInstance<Void>           instance = serializer.deserialize(bytes);
    Assert.assertTrue(instance.isEnabled(), "Instance that has no 'enabled' should be assumed enabled");
}
 
Example #21
Source File: DiscoveryExample.java    From xian with Apache License 2.0 5 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 #22
Source File: ServiceDiscoveryBuilder.java    From curator with Apache License 2.0 5 votes vote down vote up
/**
 * Build a new service discovery with the currently set values. If not set, the builder will be
 * defaulted with a {@link JsonInstanceSerializer}.
 *
 * @return new service discovery
 */
public ServiceDiscovery<T> build()
{
    if ( serializer == null )
    {
        serializer(new JsonInstanceSerializer<T>(payloadClass));
    }
    return new ServiceDiscoveryImpl<T>(client, basePath, serializer, thisInstance, watchInstances);
}
 
Example #23
Source File: ServiceDiscoverer.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * This class listens to zookeeper and updates its internal state when new model endpoints are
 * added via the MaaS service.
 *
 * @param client The zookeeper client
 * @param root The discovery root
 * @param blacklistExpirationMin The amount of time (in minutes) that a blacklisted URL can be held in the blacklist before retrying.
 */
public ServiceDiscoverer(CuratorFramework client, String root, int blacklistExpirationMin) {
  blacklist = CacheBuilder.newBuilder()
                          .concurrencyLevel(4)
                          .weakKeys()
                          .expireAfterWrite(blacklistExpirationMin, TimeUnit.MINUTES)
                          .build();
  try {
    Stat exists = client.checkExists().forPath(root);
    if(exists == null) {
      client.create().creatingParentsIfNeeded().forPath(root);
    }
  } catch (Exception e) {
    LOG.error("Unable to create path: " + e.getMessage(), e);
  }
  JsonInstanceSerializer<ModelEndpoint> serializer = new JsonInstanceSerializer<>(ModelEndpoint.class);
  serviceDiscovery = ServiceDiscoveryBuilder.builder(ModelEndpoint.class)
              .client(client)
              .basePath(root)
              .serializer(serializer)
              .build();
  cache = new TreeCache(client, root);
  cache.getListenable().addListener((client1, event) -> {
    updateState();
  });
  updateState();
}
 
Example #24
Source File: CuratorServiceDiscoveryCompatibilityTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void registeredInstancesAreSameWhenUsingServiceDiscoveryImplAndUpdatingListener() throws Throwable {
    final Endpoint endpoint = ZooKeeperTestUtil.sampleEndpoints(1).get(0);
    final CuratorFramework client =
            CuratorFrameworkFactory.builder()
                                   .connectString(zkInstance.connectString())
                                   .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                                   .build();
    client.start();
    final JsonInstanceSerializer<Void> serializer =
            new JsonInstanceSerializer<>(Void.class);
    final ServiceInstance<Void> registered = serviceInstance(endpoint);
    final ServiceDiscoveryImpl<Void> serviceDiscovery =
            new ServiceDiscoveryImpl<>(client, Z_NODE, serializer, registered, false);
    serviceDiscovery.start();
    assertInstance(registered);
    serviceDiscovery.close();
    await().untilAsserted(() -> zkInstance.assertNotExists(Z_NODE + "/foo/bar"));

    final ZooKeeperRegistrationSpec registrationSpec =
            ZooKeeperRegistrationSpec.builderForCurator("foo")
                                     .serviceId("bar")
                                     .serviceAddress("foo.com")
                                     .port(endpoint.port())
                                     .uriSpec(CURATOR_X_URI_SPEC)
                                     .build();

    final ZooKeeperUpdatingListener listener =
            ZooKeeperUpdatingListener.builder(zkInstance.connectString(), Z_NODE, registrationSpec).build();
    final Server server = Server.builder()
                                .http(endpoint.port())
                                .service("/", (ctx, req) -> HttpResponse.of(200))
                                .build();
    server.addListener(listener);
    server.start().join();
    assertInstance(registered);
    server.stop().join();
    client.close();
}
 
Example #25
Source File: TcpDiscoveryZookeeperIpFinder.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** Initializes this IP Finder by creating the appropriate Curator objects. */
private void init() {
    if (!initGuard.compareAndSet(false, true))
        return;

    String sysPropZkConnString = System.getProperty(PROP_ZK_CONNECTION_STRING);

    if (sysPropZkConnString != null && !sysPropZkConnString.trim().isEmpty())
        zkConnectionString = sysPropZkConnString;

    if (log.isInfoEnabled())
        log.info("Initializing ZooKeeper IP Finder.");

    if (curator == null) {
        A.notNullOrEmpty(zkConnectionString, String.format("ZooKeeper URL (or system property %s) cannot be null " +
            "or empty if a CuratorFramework object is not provided explicitly", PROP_ZK_CONNECTION_STRING));
        curator = CuratorFrameworkFactory.newClient(zkConnectionString, retryPolicy);
    }

    if (curator.getState() == CuratorFrameworkState.LATENT)
        curator.start();

    A.ensure(curator.getState() == CuratorFrameworkState.STARTED, "CuratorFramework can't be started.");

    discovery = ServiceDiscoveryBuilder.builder(IgniteInstanceDetails.class)
        .client(curator)
        .basePath(basePath)
        .serializer(new JsonInstanceSerializer<>(IgniteInstanceDetails.class))
        .build();
}
 
Example #26
Source File: ServiceDiscoveryConfiguration.java    From Kafdrop with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "close")
public ServiceDiscovery curatorServiceDiscovery(
   @Qualifier("serviceDiscovery") CuratorFramework curatorFramework,
   @Value("${curator.discovery.basePath:/homeadvisor/services}") String basePath) throws Exception
{
   final Class payloadClass = Object.class;
   curatorFramework.createContainers(basePath);
   return ServiceDiscoveryBuilder.builder(payloadClass)
      .client(curatorFramework)
      .basePath(basePath)
      .serializer(new JsonInstanceSerializer(payloadClass))
      .build();
}
 
Example #27
Source File: TestJsonInstanceSerializer.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void     testNoEnabledState() throws Exception
{
    JsonInstanceSerializer<Void>    serializer = new JsonInstanceSerializer<Void>(Void.class);
    byte[]                          bytes = "{}".getBytes("utf-8");

    ServiceInstance<Void>           instance = serializer.deserialize(bytes);
    Assert.assertTrue(instance.isEnabled(), "Instance that has no 'enabled' should be assumed enabled");
}
 
Example #28
Source File: CuratorServiceDiscoveryAutoConfiguration.java    From spring-cloud-zookeeper with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public InstanceSerializer<ZookeeperInstance> deprecatedInstanceSerializer() {
	return new JsonInstanceSerializer<>(ZookeeperInstance.class);
}
 
Example #29
Source File: ZookeeperServiceRegistryAutoConfiguration.java    From spring-cloud-zookeeper with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public InstanceSerializer<ZookeeperInstance> instanceSerializer() {
	return new JsonInstanceSerializer<>(ZookeeperInstance.class);
}
 
Example #30
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);
    }

}