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

The following examples show how to use org.apache.curator.x.discovery.UriSpec. 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: TestNewServiceInstance.java    From curator with Apache License 2.0 6 votes vote down vote up
public TestNewServiceInstance(String name, String id, String address, Integer port, Integer sslPort, T payload, long registrationTimeUTC, ServiceType serviceType, UriSpec uriSpec, boolean enabled, String new1, Long new2, Date new3, URI new4)
{
    name = Preconditions.checkNotNull(name, "name cannot be null");
    id = Preconditions.checkNotNull(id, "id cannot be null");

    this.new1 = new1;
    this.new2 = new2;
    this.new3 = new3;
    this.new4 = new4;
    this.serviceType = serviceType;
    this.uriSpec = uriSpec;
    this.name = name;
    this.id = id;
    this.address = address;
    this.port = port;
    this.sslPort = sslPort;
    this.payload = payload;
    this.registrationTimeUTC = registrationTimeUTC;
    this.enabled = enabled;
}
 
Example #2
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 #3
Source File: OldServiceInstance.java    From curator with Apache License 2.0 6 votes vote down vote up
/**
 * @param name name of the service
 * @param id id of this instance (must be unique)
 * @param address address of this instance
 * @param port the port for this instance or null
 * @param sslPort the SSL port for this instance or null
 * @param payload the payload for this instance or null
 * @param registrationTimeUTC the time (in UTC) of the registration
 * @param serviceType type of the service
 * @param uriSpec the uri spec or null
 */
OldServiceInstance(String name, String id, String address, Integer port, Integer sslPort, T payload, long registrationTimeUTC, ServiceType serviceType, UriSpec uriSpec)
{
    name = Preconditions.checkNotNull(name, "name cannot be null");
    id = Preconditions.checkNotNull(id, "id cannot be null");

    this.serviceType = serviceType;
    this.uriSpec = uriSpec;
    this.name = name;
    this.id = id;
    this.address = address;
    this.port = port;
    this.sslPort = sslPort;
    this.payload = payload;
    this.registrationTimeUTC = registrationTimeUTC;
}
 
Example #4
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 #5
Source File: RecordCreationTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnknownRecordCreation() throws Exception {
  UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{ssl-port}");
  ServiceInstance<JsonObject> instance = ServiceInstance.<JsonObject>builder()
      .name("foo-service")
      .payload(new JsonObject().put("foo", "bar"))
      .sslPort(42406)
      .uriSpec(uriSpec)
      .build();

  Record record = ZookeeperServiceImporter.createRecordForInstance(instance);
  assertThat(record.getName()).isEqualTo("foo-service");
  assertThat(record.getType()).isEqualTo("unknown");
  assertThat(record.getMetadata().getString("foo")).isEqualTo("bar");
  assertThat(record.getMetadata().getString("zookeeper-id")).isNotEmpty();
  assertThat(record.getLocation())
      .contains(entry("endpoint", "https://foo.com:42406"))
      .contains(entry("ssl-port", 42406));
}
 
Example #6
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 #7
Source File: TestJsonInstanceSerializerCompatibility.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testBackwardCompatibility() throws Exception
{
    JsonInstanceSerializer<TestJsonInstanceSerializer.Payload> serializer = new JsonInstanceSerializer<TestJsonInstanceSerializer.Payload>(TestJsonInstanceSerializer.Payload.class, true, true);
    ServiceInstance<TestJsonInstanceSerializer.Payload> instance = new ServiceInstance<TestJsonInstanceSerializer.Payload>("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false);
    byte[] bytes = serializer.serialize(instance);

    instance = serializer.deserialize(bytes);
    Assert.assertTrue(instance.isEnabled());    // passed false for enabled in the ctor but that is lost with compatibleSerializationMode

    ObjectMapper mapper = new ObjectMapper();
    JavaType type = mapper.getTypeFactory().constructType(OldServiceInstance.class);
    OldServiceInstance rawServiceInstance = mapper.readValue(bytes, type);
    TestJsonInstanceSerializer.Payload.class.cast(rawServiceInstance.getPayload()); // just to verify that it's the correct type
    //noinspection unchecked
    OldServiceInstance<TestJsonInstanceSerializer.Payload> check = (OldServiceInstance<TestJsonInstanceSerializer.Payload>)rawServiceInstance;
    Assert.assertEquals(check.getName(), instance.getName());
    Assert.assertEquals(check.getId(), instance.getId());
    Assert.assertEquals(check.getAddress(), instance.getAddress());
    Assert.assertEquals(check.getPort(), instance.getPort());
    Assert.assertEquals(check.getSslPort(), instance.getSslPort());
    Assert.assertEquals(check.getPayload(), instance.getPayload());
    Assert.assertEquals(check.getRegistrationTimeUTC(), instance.getRegistrationTimeUTC());
    Assert.assertEquals(check.getServiceType(), instance.getServiceType());
    Assert.assertEquals(check.getUriSpec(), instance.getUriSpec());
}
 
Example #8
Source File: TestJsonInstanceSerializerCompatibility.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testForwardCompatibility() throws Exception
{
    OldServiceInstance<TestJsonInstanceSerializer.Payload> oldInstance = new OldServiceInstance<TestJsonInstanceSerializer.Payload>("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"));
    ObjectMapper mapper = new ObjectMapper();
    byte[] oldJson = mapper.writeValueAsBytes(oldInstance);

    JsonInstanceSerializer<TestJsonInstanceSerializer.Payload> serializer = new JsonInstanceSerializer<TestJsonInstanceSerializer.Payload>(TestJsonInstanceSerializer.Payload.class);
    ServiceInstance<TestJsonInstanceSerializer.Payload> instance = serializer.deserialize(oldJson);
    Assert.assertEquals(oldInstance.getName(), instance.getName());
    Assert.assertEquals(oldInstance.getId(), instance.getId());
    Assert.assertEquals(oldInstance.getAddress(), instance.getAddress());
    Assert.assertEquals(oldInstance.getPort(), instance.getPort());
    Assert.assertEquals(oldInstance.getSslPort(), instance.getSslPort());
    Assert.assertEquals(oldInstance.getPayload(), instance.getPayload());
    Assert.assertEquals(oldInstance.getRegistrationTimeUTC(), instance.getRegistrationTimeUTC());
    Assert.assertEquals(oldInstance.getServiceType(), instance.getServiceType());
    Assert.assertEquals(oldInstance.getUriSpec(), instance.getUriSpec());
    Assert.assertTrue(instance.isEnabled());
}
 
Example #9
Source File: TestJsonInstanceSerializerCompatibility.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testFutureChanges() throws Exception
{
    TestNewServiceInstance<String> newInstance = new TestNewServiceInstance<String>("name", "id", "address", 10, 20, "hey", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false, "what", 10101L, new Date(), new URI("http://hey"));
    byte[] newInstanceBytes = new ObjectMapper().writeValueAsBytes(newInstance);
    JsonInstanceSerializer<String> serializer = new JsonInstanceSerializer<String>(String.class);
    ServiceInstance<String> instance = serializer.deserialize(newInstanceBytes);
    Assert.assertEquals(instance.getName(), "name");
    Assert.assertEquals(instance.getPayload(), "hey");
    Assert.assertEquals(instance.isEnabled(), false);
}
 
Example #10
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 #11
Source File: TestJsonInstanceSerializerCompatibility.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompatibilityMode() throws Exception
{
    JsonInstanceSerializer<TestJsonInstanceSerializer.Payload> serializer = new JsonInstanceSerializer<TestJsonInstanceSerializer.Payload>(TestJsonInstanceSerializer.Payload.class, true, true);
    ServiceInstance<TestJsonInstanceSerializer.Payload> instance = new ServiceInstance<TestJsonInstanceSerializer.Payload>("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true);
    byte[] bytes = serializer.serialize(instance);

    OldServiceInstance<TestJsonInstanceSerializer.Payload> oldInstance = new OldServiceInstance<TestJsonInstanceSerializer.Payload>("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"));
    ObjectMapper mapper = new ObjectMapper();
    byte[] oldBytes = mapper.writeValueAsBytes(oldInstance);
    Assert.assertEquals(bytes, oldBytes, String.format("%s vs %s", new String(bytes), new String(oldBytes)));
}
 
Example #12
Source File: ZookeeperStubsRegistrar.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
protected ServiceInstance serviceInstance(StubConfiguration stubConfiguration,
		int port) {
	try {
		return ServiceInstance.builder()
				.uriSpec(new UriSpec(this.zookeeperDiscoveryProperties.getUriSpec()))
				.address("localhost").port(port).name(name(stubConfiguration))
				.build();
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
Example #13
Source File: ZookeeperBridgeTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceArrival(TestContext tc) throws Exception {
  Async async = tc.async();

  UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}");
  ServiceInstance<String> instance = ServiceInstance.<String>builder()
    .name("foo-service")
    .payload(new JsonObject().put("foo", "bar").encodePrettily())
    .port(8080)
    .uriSpec(uriSpec)
    .build();

  sd.registerServiceImporter(
    new ZookeeperServiceImporter(),
    new JsonObject().put("connection", zkTestServer.getConnectString()),
    v -> {
      tc.assertTrue(v.succeeded());
      sd.getRecords(x -> true, l -> {
        tc.assertTrue(l.succeeded());
        tc.assertTrue(l.result().size() == 0);

        vertx.executeBlocking(future -> {
          try {
            this.discovery.registerService(instance);
            future.complete();
          } catch (Exception e) {
            future.fail(e);
          }
        }, ar -> {
          tc.assertTrue(ar.succeeded());
          waitUntil(() -> serviceLookup(sd, 1), lookup -> {
            tc.assertTrue(lookup.succeeded());
            async.complete();
          });
        });
      });
    });
}
 
Example #14
Source File: ZookeeperBridgeTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegistration(TestContext tc) throws Exception {
  Async async = tc.async();

  UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}");
  ServiceInstance<String> instance = ServiceInstance.<String>builder()
    .name("foo-service")
    .payload(new JsonObject().put("foo", "bar").encodePrettily())
    .port((int) (65535 * Math.random()))
    .uriSpec(uriSpec)
    .build();

  discovery.registerService(instance);
  sd.registerServiceImporter(
    new ZookeeperServiceImporter(),
    new JsonObject().put("connection", zkTestServer.getConnectString()),
    v -> {
      if (v.failed()) {
        v.cause().printStackTrace();
      }
      tc.assertTrue(v.succeeded());

      sd.getRecords(x -> true, l -> {
        if (l.failed()) {
          l.cause().printStackTrace();
        }
        tc.assertTrue(l.succeeded());
        tc.assertTrue(l.result().size() == 1);
        tc.assertEquals("foo-service", l.result().get(0).getName());
        async.complete();
      });

    });
}
 
Example #15
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 #16
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 #17
Source File: JsonSerializer.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
private String serializeUriSpec(UriSpec uriSpec) {
	StringBuilder sb = new StringBuilder();
	for (UriSpec.Part part : uriSpec.getParts()) {
		if (part.isVariable()) {
			sb.append("{");
			sb.append(part.getValue());
			sb.append("}");
		} else {
			sb.append(part.getValue());
		}
	}

	return sb.toString();
}
 
Example #18
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();
}
 
Example #19
Source File: TestNewServiceInstance.java    From curator with Apache License 2.0 4 votes vote down vote up
public UriSpec getUriSpec()
{
    return uriSpec;
}
 
Example #20
Source File: OldServiceInstance.java    From curator with Apache License 2.0 4 votes vote down vote up
public UriSpec getUriSpec()
{
    return uriSpec;
}
 
Example #21
Source File: ServiceInstanceRegistration.java    From spring-cloud-zookeeper with Apache License 2.0 4 votes vote down vote up
public RegistrationBuilder defaultUriSpec() {
	this.builder.uriSpec(new UriSpec(DEFAULT_URI_SPEC));
	return this;
}
 
Example #22
Source File: ZooKeeperRegistrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static ServiceInstance<Object> expectedInstance(List<Server> servers, int index) {
    return new ServiceInstance<>(
            CURATOR_X_SERVICE_NAME, String.valueOf(index), CURATOR_X_ADDRESS,
            servers.get(index).activeLocalPort(), null, null,
            0, ServiceType.DYNAMIC, new UriSpec("{scheme}://{address}:{port}"), true);
}
 
Example #23
Source File: CuratorDiscoverySpecTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static ServiceInstance<?> serviceInstance(boolean enabled) {
    return new ServiceInstance<>(
            "foo", "bar", "foo.com", 100, 200, null, 0, ServiceType.DYNAMIC,
            new UriSpec("{scheme}://{address}:{port}"), enabled);
}
 
Example #24
Source File: ZookeeperBridgeTest.java    From vertx-service-discovery with Apache License 2.0 4 votes vote down vote up
@Test
public void testReconnection(TestContext tc) throws Exception {
  UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}");
  ServiceInstance<String> instance = ServiceInstance.<String>builder()
    .name("foo-service")
    .payload(new JsonObject().put("foo", "bar").encodePrettily())
    .port((int) (65535 * Math.random()))
    .uriSpec(uriSpec)
    .build();

  discovery.registerService(instance);


  AtomicBoolean importDone = new AtomicBoolean();
  sd.registerServiceImporter(
    new ZookeeperServiceImporter(),
    new JsonObject()
      .put("connection", zkTestServer.getConnectString())
      .put("connectionTimeoutMs", 10)
      .put("baseSleepTimeBetweenRetries", 10)
      .put("maxRetries", 3),
    v -> {
      if (v.failed()) {
        v.cause().printStackTrace();
        tc.fail(v.cause());
        return;
      }
      tc.assertTrue(v.succeeded());

      // The registration of the service in ZK can take some time,
      // So we must be sure the service is there
      // We retries until it's done. There is a timeout set at 10 seconds.
      fetchRecords(importDone, tc);
    });

  await().untilTrue(importDone);

  // Stop the server
  zkTestServer.stop();

  importDone.set(false);
  sd.getRecords(x -> true, l -> {
    if (l.failed()) {
      l.cause().printStackTrace();
    }
    tc.assertTrue(l.succeeded());
    tc.assertTrue(l.result().size() == 1);
    tc.assertEquals("foo-service", l.result().get(0).getName());

    importDone.set(true);
  });

  await().untilAtomic(importDone, is(true));

  zkTestServer.start();

  importDone.set(false);
  sd.getRecords(x -> true, l -> {
    if (l.failed()) {
      l.cause().printStackTrace();
    }
    tc.assertTrue(l.succeeded());
    tc.assertTrue(l.result().size() == 1);
    tc.assertEquals("foo-service", l.result().get(0).getName());

    importDone.set(true);
  });

  await().untilAtomic(importDone, is(true));

}
 
Example #25
Source File: ZookeeperBridgeTest.java    From vertx-service-discovery with Apache License 2.0 4 votes vote down vote up
@Test
@Repeat(10)
public void testServiceArrivalWithSameName(TestContext tc) throws Exception {
  Async async = tc.async();

  UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}");
  ServiceInstance<String> instance1 = ServiceInstance.<String>builder()
    .name("foo-service")
    .payload(new JsonObject().put("foo", "bar").encodePrettily())
    .port(8080)
    .uriSpec(uriSpec)
    .build();

  ServiceInstance<String> instance2 = ServiceInstance.<String>builder()
    .name("foo-service")
    .payload(new JsonObject().put("foo", "bar2").encodePrettily())
    .port(8081)
    .uriSpec(uriSpec)
    .build();

  discovery.registerService(instance1);

  sd.registerServiceImporter(
    new ZookeeperServiceImporter(),
    new JsonObject().put("connection", zkTestServer.getConnectString()),
    v -> {
      tc.assertTrue(v.succeeded());

      waitUntil(() -> serviceLookup(sd, 1), list -> {
        tc.assertTrue(list.succeeded());
        tc.assertEquals(list.result().get(0).getName(), "foo-service");
        vertx.executeBlocking(future -> {
          try {
            this.discovery.registerService(instance2);
            future.complete();
          } catch (Exception e) {
            future.fail(e);
          }
        }, ar -> {
          tc.assertTrue(ar.succeeded());
          waitUntil(() -> serviceLookup(sd, 2), lookup -> {
            tc.assertTrue(lookup.succeeded());
            tc.assertEquals(lookup.result().get(0).getName(), "foo-service");
            tc.assertEquals(lookup.result().get(1).getName(), "foo-service");
            async.complete();
          });
        });
      });
    });
}
 
Example #26
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 #27
Source File: JsonSerializer.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private UriSpec deserializeUriSpec(String rawUriSpec) {
	return new UriSpec(rawUriSpec);
}