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

The following examples show how to use org.apache.curator.x.discovery.ServiceInstanceBuilder. 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: JsonObjectSerializer.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
public ServiceInstance<JsonObject> deserialize(byte[] bytes) throws Exception {
  ServiceInstance rawServiceInstance = this.mapper.readValue(bytes, this.type);
  ServiceInstanceBuilder<JsonObject> builder = ServiceInstance.<JsonObject>builder()
      .address(rawServiceInstance.getAddress())
      .id(rawServiceInstance.getId())
      .name(rawServiceInstance.getName())
      .payload(new JsonObject(rawServiceInstance.getPayload().toString()))
      .registrationTimeUTC(rawServiceInstance.getRegistrationTimeUTC())
      .serviceType(rawServiceInstance.getServiceType());

  if (rawServiceInstance.getSslPort() != null) {
    builder.sslPort(rawServiceInstance.getSslPort());
  }
  if (rawServiceInstance.getPort() != null) {
    builder.sslPort(rawServiceInstance.getPort());
  }
  if (rawServiceInstance.getUriSpec() != null) {
    builder.uriSpec(rawServiceInstance.getUriSpec());
  }
  return builder.build();
}
 
Example #3
Source File: ZooKeeperDiscovery.java    From soabase with Apache License 2.0 6 votes vote down vote up
private ServiceInstance<Payload> buildInstance(String serviceName, HostAndPort mainPort, Payload payload, String id, String address) throws Exception
{
    ServiceInstanceBuilder<Payload> builder = ServiceInstance.<Payload>builder()
        .name(serviceName)
        .payload(payload)
        .address(mainPort.getHostText())
        .port(mainPort.getPort())
        ;
    if ( id != null )
    {
        builder = builder.id(id);
    }
    if ( address != null )
    {
        builder = builder.address(address);
    }
    else if ( bindAddress != null )
    {
        builder = builder.address(bindAddress);
    }
    return builder.build();
}
 
Example #4
Source File: JsonServiceInstanceMarshaller.java    From curator with Apache License 2.0 6 votes vote down vote up
static<T> ServiceInstance<T> readInstance(JsonNode node, DiscoveryContext<T> context) throws Exception
{
    ServiceInstanceBuilder<T> builder = ServiceInstance.builder();

    builder.name(node.get("name").asText());
    builder.id(node.get("id").asText());
    builder.address(node.get("address").asText());
    builder.registrationTimeUTC(node.get("registrationTimeUTC").asLong());
    builder.serviceType(ServiceType.valueOf(node.get("serviceType").asText()));
    builder.payload(context.unMarshallJson(node.get("payload")));

    Integer port = getInteger(node, "port");
    Integer sslPort = getInteger(node, "sslPort");
    if ( port != null )
    {
        builder.port(port);
    }
    if ( sslPort != null )
    {
        builder.sslPort(sslPort);
    }

    return builder.build();
}
 
Example #5
Source File: CuratorAdvertiser.java    From snowizard-discovery with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * This must be called before other methods are used.
 * 
 * @param port
 *            port this instance is listening on
 */
public synchronized void initListenInfo(final int port) {
    try {
        final Collection<InetAddress> ips = ServiceInstanceBuilder
                .getAllLocalIPs();
        if (Iterables.size(ips) > 0) {
            listenAddress = String.valueOf(Iterables.get(ips, 0))
                    .substring(1);
            LOGGER.debug("Found Local IP Addresses: {}, using {}", ips,
                    listenAddress);
        }
    } catch (final SocketException e) {
        LOGGER.error("Error getting local IP addresses", e);
    }

    if (Strings.isNullOrEmpty(listenAddress)) {
        LOGGER.debug("Using listenAddress from configuration file");
        listenAddress = configuration.getListenAddress();
    }

    listenPort = port;
}
 
Example #6
Source File: DrillServiceInstanceHelper.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceInstance<DrillbitEndpoint> deserialize(byte[] bytes) throws Exception {
  DrillServiceInstance i = DrillServiceInstance.parseFrom(bytes);
  ServiceInstanceBuilder<DrillbitEndpoint> b = ServiceInstance.<DrillbitEndpoint>builder();
  b.id(i.getId());
  b.name(ExecConstants.SERVICE_NAME);
  b.registrationTimeUTC(i.getRegistrationTimeUTC());
  b.payload(i.getEndpoint());
  return b.build();
}
 
Example #7
Source File: HelloServerConfig.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
@Bean(name = "service-instance")
public ServiceInstance<RpcPayload> serviceInstance() throws Exception {
	ServiceInstanceBuilder<RpcPayload> instance = ServiceInstance.builder();
	instance.name(env.getProperty("rpc.server.service.name"))
			.uriSpec(new UriSpec(env.getProperty("rpc.server.uri.spec")))
			.payload(this.payload()).port(this.port())
			.id(this.instanceId()).address(this.ip());
	return instance.build();
}
 
Example #8
Source File: ServiceInstanceHelper.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceInstance<NodeEndpoint> deserialize(byte[] bytes) throws Exception {
  DremioServiceInstance i = DremioServiceInstance.parseFrom(bytes);
  ServiceInstanceBuilder<NodeEndpoint> b = ServiceInstance.<NodeEndpoint>builder();
  b.id(i.getId());
  b.name(i.getName());
  b.registrationTimeUTC(i.getRegistrationTimeUTC());
  b.payload(i.getEndpoint());
  return b.build();
}
 
Example #9
Source File: ServiceDiscoveryIntegrationTest.java    From metron with Apache License 2.0 5 votes vote down vote up
private ServiceInstance<ModelEndpoint> createInstance(ModelEndpoint ep) throws Exception {
  URL url = new URL(ep.getEndpoint().getUrl());
  ServiceInstanceBuilder<ModelEndpoint> builder = ServiceInstance.<ModelEndpoint> builder()
          .address(url.getHost())
          .id(ep.getContainerId())
          .name(ep.getName())
          .port(url.getPort())
          .registrationTimeUTC(System.currentTimeMillis())
          .serviceType(ServiceType.STATIC)
          .payload(ep)
          ;
  return builder.build();
}
 
Example #10
Source File: RpcServerConfiguration.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
/**
 * 这个bean启动后会独占线程,导致其他的bean无法执行。所以必须保证这个bean在最后才能够执行。
 * @return
 * @throws Exception
 */
@Bean(initMethod = "start", destroyMethod = "stop")
public ServerRunner serverRunner()
		throws Exception {
	String ip = this.ip;
	if (ip == null)
		ip = new IpPortResolver().getIpV4Address();

	String instanceId = this.ip + ":" + this.port;
	
	CuratorFramework curatorFramework =CuratorFrameworkFactory.builder()
			.connectString(this.connectString)
			.sessionTimeoutMs(this.sessionTimeoutMs)
			.connectionTimeoutMs(this.connectionTimeoutMs)
			.retryPolicy(this.retryPolicy())
			.aclProvider(this.aclProvider()).authorization(this.authInfo())
			.build();
	InstanceSerializer<RpcPayload> serializer = new JsonSerializer();

	TServerTransport transport = new TServerSocket(this.port);

	TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport);
	args.transportFactory(new TTransportFactory());
	args.protocolFactory(new TBinaryProtocol.Factory());

	TProcessor processor= new TProtobufProcessor();		
	args.processor(processor);
	
	args.executorService(new ThreadPoolExecutor(this.minTheads,
			this.maxTheads, this.keepAliveTime, TimeUnit.SECONDS,
			new SynchronousQueue<Runnable>()));

	TServer server = new TThreadPoolServer(args);

	ServiceInstanceBuilder<RpcPayload> instanceBuilder = ServiceInstance
			.builder();
	instanceBuilder.name(this.serviceName)
			.uriSpec(new UriSpec(this.uriSpec)).payload(this.payload())
			.port(port).id(instanceId).address(ip);

	ServiceDiscoveryBuilder<RpcPayload> discoveryBuilder = ServiceDiscoveryBuilder
			.builder(RpcPayload.class);
	discoveryBuilder.client(curatorFramework).basePath(zkBasePath)
			.serializer(serializer).thisInstance(instanceBuilder.build())
			.build();
	return ServerRunner
			.newBuilder()
			.server(server)
			.curatorFramework(curatorFramework)
			.serviceDiscovery(discoveryBuilder.build())
			.zookeeperDeferRegisterPeriod(this.zookeeperDeferRegisterPeriod)
			.zookeeperUnregisterPeriod(this.zookeeperUnregisterPeriod).build();
}
 
Example #11
Source File: StellarMaaSIntegrationTest.java    From metron with Apache License 2.0 4 votes vote down vote up
@BeforeAll
public static void setup() throws Exception {
  UnitTestHelper.setJavaLoggingLevel(WebApplicationImpl.class, Level.WARNING);
  MockDGAModel.start(8282);
  testZkServer = new TestingServer(true);
  zookeeperUrl = testZkServer.getConnectString();
  RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  client = CuratorFrameworkFactory.newClient(zookeeperUrl, retryPolicy);
  client.start();
  context = new Context.Builder()
          .with(Context.Capabilities.ZOOKEEPER_CLIENT, () -> client)
          .build();
  MaaSConfig config = ConfigUtil.INSTANCE.read(client, "/metron/maas/config", new MaaSConfig(), MaaSConfig.class);
  discoverer = new ServiceDiscoverer(client, config.getServiceRoot());
  discoverer.start();
  endpointUrl = new URL("http://localhost:8282");
  ModelEndpoint endpoint = new ModelEndpoint();
  {
    endpoint.setName("dga");
    endpoint.setContainerId("0");
    Endpoint ep = new Endpoint();
    ep.setUrl(endpointUrl.toString());
    endpoint.setEndpoint(ep);
    endpoint.setVersion("1.0");
  }
  ;

  ServiceInstanceBuilder<ModelEndpoint> builder = ServiceInstance.<ModelEndpoint>builder()
          .address(endpointUrl.getHost())
          .id("0")
          .name("dga")
          .port(endpointUrl.getPort())
          .registrationTimeUTC(System.currentTimeMillis())
          .serviceType(ServiceType.STATIC)
          .payload(endpoint);
  final ServiceInstance<ModelEndpoint> instance = builder.build();
  discoverer.getServiceDiscovery().registerService(instance);
  //wait til the endpoint is installed...
  for(int i = 0;i < 10;++i) {
    try {
      Object o = discoverer.getEndpoint("dga");
      if(o != null) {
        break;
      }
    }
    catch(Exception e) {

    }
    Thread.sleep(1000);
  }
}
 
Example #12
Source File: ServiceInstanceRegistration.java    From spring-cloud-zookeeper with Apache License 2.0 4 votes vote down vote up
public ServiceInstanceRegistration(
		ServiceInstanceBuilder<ZookeeperInstance> builder) {
	this.builder = builder;
}
 
Example #13
Source File: ServiceInstanceRegistration.java    From spring-cloud-zookeeper with Apache License 2.0 4 votes vote down vote up
public RegistrationBuilder(ServiceInstanceBuilder<ZookeeperInstance> builder) {
	this.builder = builder;
}
 
Example #14
Source File: FixedJsonInstanceSerializer.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
@Override
public ServiceInstance<T> deserialize(final byte[] pBytes) throws Exception {
    final ByteArrayInputStream bais = new ByteArrayInputStream(pBytes);
    final JsonNode rootNode = mMapper.readTree(bais);
    final ServiceInstanceBuilder<T> builder = ServiceInstance.builder();
    {
        final String address = getTextField(rootNode, "address");
        if (address != null) {
            builder.address(address);
        }
    }
    {
        final String id = getTextField(rootNode, "id");
        if (id != null) {
            builder.id(id);
        }
    }
    {
        final String name = getTextField(rootNode, "name");
        if (name != null) {
            builder.name(name);
        }
    }
    {
        final Integer port = getIntegerField(rootNode, "port");
        if (port != null) {
            builder.port(port);
        }
    }
    {
        final Integer sslPort = getIntegerField(rootNode, "sslPort");
        if (sslPort != null) {
            builder.sslPort(sslPort);
        }
    }
    {
        final Long registrationTimeUTC = getLongField(rootNode, "registrationTimeUTC");
        if (registrationTimeUTC != null) {
            builder.registrationTimeUTC(registrationTimeUTC);
        }
    }
    {
        final T payload = getObject(rootNode, "payload", mPayloadClass);
        if (payload != null) {
            builder.payload(payload);
        }
    }
    {
        final ServiceType serviceType = getObject(rootNode, "serviceType", ServiceType.class);
        if (serviceType != null) {
            builder.serviceType(serviceType);
        }
    }
    {
        final UriSpec uriSpec = getObject(rootNode, "uriSpec", UriSpec.class);
        if (uriSpec != null) {
            builder.uriSpec(uriSpec);
        }
    }
    return builder.build();
}