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

The following examples show how to use org.apache.curator.x.discovery.ServiceInstance. 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: 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 #2
Source File: TestDownInstanceManager.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpiration() throws Exception
{
    ServiceInstance<Void> instance1 = ServiceInstance.<Void>builder().name("hey").id("1").build();
    ServiceInstance<Void> instance2 = ServiceInstance.<Void>builder().name("hey").id("2").build();

    DownInstanceManager<Void> downInstanceManager = new DownInstanceManager<Void>(debugDownInstancePolicy);

    downInstanceManager.add(instance1);
    Assert.assertFalse(downInstanceManager.apply(instance1));
    Assert.assertTrue(downInstanceManager.apply(instance2));

    Thread.sleep(debugDownInstancePolicy.getTimeoutMs());

    Assert.assertTrue(downInstanceManager.apply(instance1));
    Assert.assertTrue(downInstanceManager.apply(instance2));
}
 
Example #3
Source File: ZkApplicationDiscovery.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceProvider<NodeStatus> load(String name) throws Exception {
    return new InstanceProvider<NodeStatus>() {
        @Override
        public List<ServiceInstance<NodeStatus>> getInstances() throws Exception {
            return (List<ServiceInstance<NodeStatus>>) serviceDiscovery.queryForInstances(name);
        }

        @Override
        public ServiceInstance<NodeStatus> getInstance(String nodeId) {
            try {
                return serviceDiscovery.queryForInstance(name, nodeId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example #4
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 #5
Source File: RecordCreationTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpRecordCreation() throws Exception {
  UriSpec uriSpec = new UriSpec("{scheme}://example.com:{port}/foo");
  ServiceInstance<JsonObject> instance = ServiceInstance.<JsonObject>builder()
      .name("foo-service")
      .payload(new JsonObject().put("foo", "bar").put("service-type", "http-endpoint"))
      .port(8080)
      .uriSpec(uriSpec)
      .build();

  Record record = ZookeeperServiceImporter.createRecordForInstance(instance);
  assertThat(record.getName()).isEqualTo("foo-service");
  assertThat(record.getType()).isEqualTo("http-endpoint");
  assertThat(record.getMetadata().getString("foo")).isEqualTo("bar");
  assertThat(record.getMetadata().getString("zookeeper-id")).isNotEmpty();
  assertThat(record.getLocation())
      .contains(entry("endpoint", "http://example.com:8080/foo"))
      .contains(entry("port", 8080));
}
 
Example #6
Source File: ServiceDiscoveryImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
/**
 * Return a service instance POJO
 *
 * @param name name of the service
 * @param id ID of the instance
 * @return the instance or <code>null</code> if not found
 * @throws Exception errors
 */
@Override
public ServiceInstance<T> queryForInstance(String name, String id) throws Exception
{
    String path = pathForInstance(name, id);
    try
    {
        byte[] bytes = client.getData().forPath(path);
        return serializer.deserialize(bytes);
    }
    catch ( KeeperException.NoNodeException ignore )
    {
        // ignore
    }
    return null;
}
 
Example #7
Source File: ZkApplicationDiscovery.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public List<ApplicationInstance> all(String name) {
    List<ApplicationInstance> applicationInstanceList = new ArrayList<>();
    try {
        List<ServiceInstance<NodeStatus>> allInstances = serviceProviders.get(name).getAllInstances();
        if (allInstances.isEmpty()) {
            allInstances = nonCachedInstanceProviders.get(name).getInstances();
        }
        for (ServiceInstance<NodeStatus> serviceInstance : allInstances) {
            applicationInstanceList.add(ZkServiceInstanceAdaptor.applicationInstance(serviceInstance));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return applicationInstanceList;
}
 
Example #8
Source File: ZooKeeperDiscovery.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<DiscoveryInstance> getAllInstances(String serviceName)
{
    try
    {
        // TODO - validate service name
        ServiceProvider<Payload> provider = providers.get(serviceName);
        Collection<ServiceInstance<Payload>> allInstances = provider.getAllInstances();
        return Collections2.transform(allInstances, new Function<ServiceInstance<Payload>, DiscoveryInstance>()
        {
            @Nullable
            @Override
            public DiscoveryInstance apply(@Nullable ServiceInstance<Payload> instance)
            {
                return toSoaInstance(instance);
            }
        });
    }
    catch ( Exception e )
    {
        log.error("Could not get service: " + serviceName, e);
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: ZooKeeperDiscovery.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
public void setForcedState(String serviceName, String instanceId, ForcedState forcedState)
{
    try
    {
        ServiceInstance<Payload> foundInstance = discovery.queryForInstance(serviceName, instanceId);
        if ( foundInstance != null )
        {
            DiscoveryInstance soaInstance = toSoaInstance(foundInstance);
            Payload oldPayload = foundInstance.getPayload();
            Payload newPayload = new Payload(null, oldPayload.getAdminPort(), oldPayload.getMetaData(), forcedState, oldPayload.getHealthyState());
            ServiceInstance<Payload> updatedInstance = buildInstance(serviceName, HostAndPort.fromParts(soaInstance.getHost(), soaInstance.getPort()), newPayload, instanceId, soaInstance.getHost());
            discovery.updateService(updatedInstance);
        } // TODO else?
    }
    catch ( Exception e )
    {
        log.error("Could not update service: " + (serviceName + ":" + instanceId), e);
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: DiscoveryResource.java    From curator with Apache License 2.0 6 votes vote down vote up
private Response internalGet(String name, String id, boolean addDeprecationHeader)
{
    try
    {
        ServiceInstance<T> instance = context.getServiceDiscovery().queryForInstance(name, id);
        if ( instance == null )
        {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        Response.ResponseBuilder builder = Response.ok(instance);
        if ( addDeprecationHeader )
        {
            builder = builder.header("Warning", "This API has been deprecated. Please see the updated spec for the replacement API.");
        }
        return builder.build();
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        log.error(String.format("Trying to get instance (%s) from service (%s)", id, name), e);
        return Response.serverError().build();
    }
}
 
Example #11
Source File: TestDownInstanceManager.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreshold() throws Exception
{
    ServiceInstance<Void> instance1 = ServiceInstance.<Void>builder().name("hey").id("1").build();
    ServiceInstance<Void> instance2 = ServiceInstance.<Void>builder().name("hey").id("2").build();

    DownInstanceManager<Void> downInstanceManager = new DownInstanceManager<Void>(debugMultiDownInstancePolicy);
    Assert.assertTrue(downInstanceManager.apply(instance1));
    Assert.assertTrue(downInstanceManager.apply(instance2));

    downInstanceManager.add(instance1);
    Assert.assertTrue(downInstanceManager.apply(instance1));
    Assert.assertTrue(downInstanceManager.apply(instance2));

    downInstanceManager.add(instance1);
    Assert.assertFalse(downInstanceManager.apply(instance1));
    Assert.assertTrue(downInstanceManager.apply(instance2));
}
 
Example #12
Source File: ZkUnitDiscovery.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public InstanceProvider<UnitProxy> load(String unitFullName) throws Exception {
    return new InstanceProvider<UnitProxy>() {
        @Override
        public List<ServiceInstance<UnitProxy>> getInstances() throws Exception {
            return (List<ServiceInstance<UnitProxy>>) serviceDiscovery.queryForInstances(unitFullName);
        }

        @Override
        public ServiceInstance<UnitProxy> getInstance(String id) {
            try {
                return serviceDiscovery.queryForInstance(unitFullName, id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example #13
Source File: ServiceRegister.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
public void regService(String host, int port) throws Exception {

    haContext.startCuratorFramework();
    ServiceInstance<Void> serviceInstance = ServiceInstance.<Void>builder()
        .address(host)
        .port(port)
        .name(HAContext.SENTRY_SERVICE_REGISTER_NAMESPACE)
        .build();

    InstanceSerializer<Void> instanceSerializer = new FixedJsonInstanceSerializer<Void>(Void.class);
    ServiceDiscoveryBuilder.builder(Void.class)
        .basePath(HAContext.SENTRY_SERVICE_REGISTER_NAMESPACE)
        .client(haContext.getCuratorFramework())
        .serializer(instanceSerializer)
        .thisInstance(serviceInstance)
        .build()
        .start();
  }
 
Example #14
Source File: ZkServiceRegistry.java    From xian with Apache License 2.0 6 votes vote down vote up
public static void unregisterService(String serviceName, String clientId) {
    try {
        if (registry != null) {
            synchronized (lock) {
                ServiceInstance<NodeStatus> instance = registry.serviceDiscovery.queryForInstance(serviceName, clientId);
                if (instance != null) {
                    registry.serviceDiscovery.unregisterService(instance);
                } else {
                    LOG.warn("你要注销的服务不存在或已经被注销了,服务id:" + clientId);
                }
            }
        } else {
            LOG.error("服务注册机已经停止,说明本机所有服务已经全部注销,所以没必要再单独注销服务了。", new Throwable());
        }
    } catch (Throwable e) {
        LOG.error(e);
    }
}
 
Example #15
Source File: JsonServiceInstanceMarshaller.java    From curator with Apache License 2.0 6 votes vote down vote up
static<T> ObjectNode writeInstance(ObjectMapper mapper, ServiceInstance<T> instance, DiscoveryContext<T> context)
{
    ObjectNode  node = mapper.createObjectNode();
    node.put("name", instance.getName());
    node.put("id", instance.getId());
    node.put("address", instance.getAddress());
    putInteger(node, "port", instance.getPort());
    putInteger(node, "sslPort", instance.getSslPort());
    node.put("registrationTimeUTC", instance.getRegistrationTimeUTC());
    node.put("serviceType", instance.getServiceType().name());
    try
    {
        context.marshallJson(node, "payload", instance.getPayload());
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        throw new WebApplicationException(e);
    }

    return node;
}
 
Example #16
Source File: TestDownInstanceManager.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreshold() throws Exception
{
    ServiceInstance<Void> instance1 = ServiceInstance.<Void>builder().name("hey").id("1").build();
    ServiceInstance<Void> instance2 = ServiceInstance.<Void>builder().name("hey").id("2").build();

    DownInstanceManager<Void> downInstanceManager = new DownInstanceManager<Void>(debugMultiDownInstancePolicy);
    Assert.assertTrue(downInstanceManager.apply(instance1));
    Assert.assertTrue(downInstanceManager.apply(instance2));

    downInstanceManager.add(instance1);
    Assert.assertTrue(downInstanceManager.apply(instance1));
    Assert.assertTrue(downInstanceManager.apply(instance2));

    downInstanceManager.add(instance1);
    Assert.assertFalse(downInstanceManager.apply(instance1));
    Assert.assertTrue(downInstanceManager.apply(instance2));
}
 
Example #17
Source File: AbstractTransportPool.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
@Override
public TTransport create(ServiceInstance<RpcPayload> instance)
        throws Exception {
    TTransport transport = this.createNativeTransport(instance);
    try {
        transport.open();
    } catch (TException ex) {
        LOG.warn(
                "Error when creating new transport on server: "
                        + instance.getAddress() + ":" + instance.getPort(),
                ex);
        markError(instance);
        throw ex;
    }
    return new ManagedTransport(transport, instance);
}
 
Example #18
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 #19
Source File: ZkUnitDiscovery.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public UnitInstance firstInstance(String unitFullName) {
    try {
        Collection<ServiceInstance<UnitProxy>> instances = serviceProviders.getUnchecked(unitFullName).getAllInstances();
        if (instances.isEmpty())
            instances = nonCachedInstanceProviders.get(unitFullName).getInstances();
        if (instances.isEmpty()) return null;
        ServiceInstance<UnitProxy> zkServiceInstance = instances.iterator().next();
        return ZkServiceInstanceAdaptor.unitInstance(zkServiceInstance);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: RoundRobinStrategy.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceInstance<T> getInstance(InstanceProvider<T> instanceProvider) throws Exception
{
    List<ServiceInstance<T>>    instances = instanceProvider.getInstances();
    if ( instances.size() == 0 )
    {
        return null;
    }
    int                         thisIndex = Math.abs(index.getAndIncrement());
    return instances.get(thisIndex % instances.size());
}
 
Example #21
Source File: ZooKeeperDiscovery.java    From soabase with Apache License 2.0 5 votes vote down vote up
private DiscoveryInstance toSoaInstance(ServiceInstance<Payload> instance)
{
    if ( instance == null )
    {
        return null;
    }

    Payload payload = instance.getPayload();
    int port = Objects.firstNonNull(instance.getPort(), Objects.firstNonNull(instance.getSslPort(), 0));
    return new DiscoveryInstanceImpl(instance.getId(), instance.getAddress(), port, instance.getSslPort() != null, payload);
}
 
Example #22
Source File: ZkServiceInstanceAdaptor.java    From xian with Apache License 2.0 5 votes vote down vote up
public static ServiceInstance<UnitProxy> thisCuratorServiceInstance(Unit unit) throws Exception {
    String fullUnitName = Unit.fullName(unit);
    return ServiceInstance.<UnitProxy>builder()
            .address(EnvUtil.getLocalIp())
            .enabled(true)
            .id(new UnitInstanceIdBean(fullUnitName, LocalNodeManager.LOCAL_NODE_ID).getUnitInstanceId())
            .name(fullUnitName)
            .port(Node.RPC_PORT)
            .payload(UnitProxy.create(unit))
            .serviceType(ServiceType.DYNAMIC)
            .build();
}
 
Example #23
Source File: TestStringsWithRestEasy.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void     testRegisterService() throws Exception
{
    RestEasySingletons  restEasySingletons = RestEasyApplication.singletonsRef.get();

    ServiceInstance<String> service = ServiceInstance.<String>builder()
        .name("test")
        .payload("From Test")
        .serviceType(ServiceType.STATIC)
        .build();

    ByteArrayOutputStream           out = new ByteArrayOutputStream();
    restEasySingletons.serviceInstanceMarshallerSingleton.writeTo(service, null, null, null, null, null, out);

    getJson("http://localhost:" + port + "/v1/service/test/" + service.getId(), new String(out.toByteArray()));

    String json = getJson("http://localhost:" + port + "/v1/service", null);
    ServiceNames names = restEasySingletons.serviceNamesMarshallerSingleton.readFrom(ServiceNames.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, new ByteArrayInputStream(json.getBytes()));
    Assert.assertEquals(names.getNames(), Lists.newArrayList("test"));

    json = getJson("http://localhost:" + port + "/v1/service/test", null);
    ServiceInstances<String> instances = restEasySingletons.serviceInstancesMarshallerSingleton.readFrom(null, null, null, null, null, new ByteArrayInputStream(json.getBytes()));
    Assert.assertEquals(instances.getServices().size(), 1);
    Assert.assertEquals(instances.getServices().get(0), service);

    // Retrieve single instance
    json = getJson("http://localhost:" + port + "/v1/service/test/" + service.getId(), null);
    ServiceInstance<String> instance = restEasySingletons.serviceInstanceMarshallerSingleton.readFrom(null, null, null, null, null, new ByteArrayInputStream(json.getBytes()));
    Assert.assertEquals(instance, service);

}
 
Example #24
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
public void doAdvertise(Service<byte[]> service, boolean flag)
{
  try {
    new EnsurePath(basePath).ensure(curatorFramework.getZookeeperClient());

    ServiceInstance<byte[]> instance = getInstance(service);
    if (flag) {
      discovery.registerService(instance);
    } else {
      discovery.unregisterService(instance);
    }
  } catch (Exception e) {
    throw Throwables.propagate(e);
  }
}
 
Example #25
Source File: TestServiceRegistrar.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
public ServiceInstance serviceInstance() {
	try {
		return ServiceInstance.builder()
				.uriSpec(new UriSpec("{scheme}://{address}:{port}/"))
				.address("localhost").port(this.serverPort).name("testInstance")
				.build();
	}
	catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #26
Source File: ZkServiceInstanceAdaptor.java    From xian with Apache License 2.0 5 votes vote down vote up
public static ServiceInstance<UnitProxy> curatorServiceInstance(UnitInstance unitInstance) {
    try {
        return ServiceInstance.<UnitProxy>builder()
                .address(unitInstance.getAddress())
                .enabled(true)
                .id(unitInstance.getId())
                .name(unitInstance.getName())
                .port(unitInstance.getPort())
                .payload(unitInstance.getPayload())
                .build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: ZkServiceInstanceAdaptor.java    From xian with Apache License 2.0 5 votes vote down vote up
public static ServiceInstance<NodeStatus> curatorServiceInstance(ApplicationInstance applicationInstance) {
    try {
        return ServiceInstance.<NodeStatus>builder()
                .address(/*applicationInstance.getPayload().getHost()*/applicationInstance.getAddress())
                .enabled(true)
                .id(applicationInstance.getId())
                .name(applicationInstance.getName())
                .port(applicationInstance.getPort())
                .payload(applicationInstance.getPayload())
                .build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #28
Source File: MockServiceDiscovery.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceInstance<T> queryForInstance(String name, String id) throws Exception
{
    Collection<ServiceInstance<T>> instances = services.get(name);
    for ( ServiceInstance<T> instance : instances )
    {
        if ( instance.getId().equals(id) )
        {
            return instance;
        }
    }
    return null;
}
 
Example #29
Source File: ZookeeperServiceDiscoveryOps.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static NetworkService toNetworkService(
    final NetworkService.Type serviceType,
    final ServiceInstance<Void> serviceInstance) {

    NetworkService ns = new NetworkService();
    ns.setType(serviceType);
    ns.setAddress(serviceInstance.getAddress());
    return ns;
}
 
Example #30
Source File: ZKAssistedDiscovery.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
JacksonInstanceSerializer(ObjectReader objectReader, ObjectWriter objectWriter,
    TypeReference<ServiceInstance<T>> typeRef)
{
  this.objectReader = objectReader;
  this.objectWriter = objectWriter;
  this.typeRef = typeRef;
}