io.vertx.servicediscovery.Record Java Examples
The following examples show how to use
io.vertx.servicediscovery.Record.
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: HttpEndpoint.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
/** * Same as {@link #createRecord(String, String, int, String, JsonObject)} but let you configure whether or not the * service is using {@code https}. * * @param name the service name * @param ssl whether or not the service is using HTTPS * @param host the host (IP or DNS name), it must be the _public_ IP / name * @param port the port, it must be the _public_ port * @param root the path of the service, "/" if not set * @param metadata additional metadata * @return the created record */ static Record createRecord(String name, boolean ssl, String host, int port, String root, JsonObject metadata) { Objects.requireNonNull(name); Objects.requireNonNull(host); if (root == null) { root = "/"; } Record record = new Record().setName(name) .setType(TYPE) .setLocation(new HttpLocation() .setSsl(ssl).setHost(host).setPort(port).setRoot(root).toJson()); if (metadata != null) { record.setMetadata(metadata); } return record; }
Example #2
Source File: DockerLinksServiceImporter.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@Override public void close(Handler<Void> completionHandler) { List<Future> list = new ArrayList<>(); for (Record record : records) { publisher.unpublish(record.getRegistration(), v -> list.add(v.succeeded() ? Future.succeededFuture() : Future.failedFuture(v.cause()))); } CompositeFuture.all(list).onComplete(ar -> { if (ar.succeeded()) { LOGGER.info("Successfully closed the service importer " + this); } else { LOGGER.error("A failure has been caught while stopping " + this, ar.cause()); } if (completionHandler != null) { completionHandler.handle(null); } } ); }
Example #3
Source File: EventBusService.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
/** * Lookup for a service record and if found, retrieve it and return the service object (used to consume the service). * This is a convenient method to avoid explicit lookup and then retrieval of the service. This method requires to * have the {@code clientClass} set with the expected set of client. This is important for usages not using Java so * you can pass the expected type. * * @param discovery the service discovery * @param filter the filter * @param clientClass the client class * @param conf the configuration for message delivery * @param resultHandler the result handler * @param <T> the type of the client class * @return {@code null} - do not use */ static <T> T getServiceProxy(ServiceDiscovery discovery, Function<Record, Boolean> filter, Class<T> clientClass, JsonObject conf, Handler<AsyncResult<T>> resultHandler) { discovery.getRecord(filter, ar -> { if (ar.failed()) { resultHandler.handle(Future.failedFuture(ar.cause())); } else { if (ar.result() == null) { resultHandler.handle(Future.failedFuture("Cannot find service matching with " + filter)); } else { ServiceReference service = discovery.getReferenceWithConfiguration(ar.result(), conf); resultHandler.handle(Future.succeededFuture(service.getAs(clientClass))); } } }); return null; }
Example #4
Source File: EventBusService.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
/** * Lookup for a service record and if found, retrieve it and return the service object (used to consume the service). * This is a convenient method to avoid explicit lookup and then retrieval of the service. This method requires to * have the {@code clientClass} set with the expected set of client. This is important for usages not using Java so * you can pass the expected type. * * @param discovery the service discovery * @param filter the filter * @param clientClass the client class * @param resultHandler the result handler * @param <T> the type of the client class * @return {@code null} - do not use */ static <T> T getServiceProxy(ServiceDiscovery discovery, Function<Record, Boolean> filter, Class<T> clientClass, Handler<AsyncResult<T>> resultHandler) { discovery.getRecord(filter, ar -> { if (ar.failed()) { resultHandler.handle(Future.failedFuture(ar.cause())); } else { if (ar.result() == null) { resultHandler.handle(Future.failedFuture("Cannot find service matching with " + filter)); } else { ServiceReference service = discovery.getReference(ar.result()); resultHandler.handle(Future.succeededFuture(service.getAs(clientClass))); } } }); return null; }
Example #5
Source File: DefaultServiceDiscoveryBackend.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@Override public void getRecord(String uuid, Handler<AsyncResult<Record>> resultHandler) { retrieveRegistry(reg -> { if (reg.failed()) { resultHandler.handle(failure(reg.cause())); } else { reg.result().get(uuid, ar -> { if (ar.succeeded()) { if (ar.result() != null) { resultHandler.handle(Future.succeededFuture(new Record(new JsonObject(ar.result())))); } else { resultHandler.handle(Future.succeededFuture(null)); } } else { resultHandler.handle(Future.failedFuture(ar.cause())); } }); } }); }
Example #6
Source File: AuditVerticleTest.java From vertx-microservices-workshop with Apache License 2.0 | 6 votes |
@Before public void setUp(TestContext tc) { Async async = tc.async(); vertx = Vertx.vertx(); Record record = MessageSource.createRecord("portfolio-events", "portfolio", JsonObject .class); ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions() .setBackendConfiguration(new JsonObject().put("backend-name", DefaultServiceDiscoveryBackend.class.getName()))) .publish(record, r -> { if (r.failed()) { r.cause().printStackTrace(); tc.fail(r.cause()); } vertx.deployVerticle(AuditVerticle.class.getName(), new DeploymentOptions().setConfig(CONFIGURATION), tc.asyncAssertSuccess(s -> async.complete())); }); }
Example #7
Source File: ServiceDiscoveryRestEndpoint.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
private void update(RoutingContext routingContext) { String uuid = routingContext.request().getParam("uuid"); JsonObject json = routingContext.getBodyAsJson(); Record record = new Record(json); if (!uuid.equals(record.getRegistration())) { routingContext.fail(400); return; } discovery.update(record, ar -> { if (ar.failed()) { routingContext.fail(ar.cause()); } else { routingContext.response().setStatusCode(200) .putHeader("Content-Type", "application/json") .end(ar.result().toJson().toString()); } }); }
Example #8
Source File: MicroserviceVerticle.java From microtrader with MIT License | 6 votes |
@Override public void stop(Future<Void> future) throws Exception { List<Future> futures = new ArrayList<>(); for (Record record : registeredRecords) { Future<Void> unregistrationFuture = Future.future(); futures.add(unregistrationFuture); discovery.unpublish(record.getRegistration(), unregistrationFuture.completer()); } if (futures.isEmpty()) { discovery.close(); future.complete(); } else { CompositeFuture composite = CompositeFuture.all(futures); composite.setHandler(ar -> { discovery.close(); if (ar.failed()) { future.fail(ar.cause()); } else { future.complete(); } }); } }
Example #9
Source File: DockerService.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
public DockerService(Container container, String host) { this.host = host; containerId = container.getId(); containerNames = Arrays.stream(container.getNames()).collect(Collectors.toList()); if (!containerNames.isEmpty()) { name = containerNames.get(0); } else { name = containerId; } for (ContainerPort port : container.getPorts()) { Record record = createRecord(container, port); if (record != null) { records.add(record); } } }
Example #10
Source File: KubernetesServiceImporterTest.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@Test public void testUnknownExternalServiceRecordCreation() throws Exception { // JDBC Example int servicePort = 5432; Service service = getExternalService(servicePort); Record record = KubernetesServiceImporter.createRecord(new JsonObject(mapper.writeValueAsString(service))); assertThat(record).isNotNull(); assertThat(record.getName()).isEqualTo("my-service"); assertThat(record.getMetadata().getString("kubernetes.name")).isEqualTo("my-service"); assertThat(record.getMetadata().getString("kubernetes.namespace")).isEqualTo("my-project"); assertThat(record.getMetadata().getString("kubernetes.uuid")).isEqualTo("uuid"); assertThat(record.getType()).isEqualTo(JDBCDataSource.TYPE); assertThat(record.getLocation().getString("host")).isEqualTo("my-external-service"); assertThat(record.getLocation().getInteger("port")).isEqualTo(servicePort); }
Example #11
Source File: KubernetesServiceImporterTest.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@Test public void testHttpExternalServiceRecordCreation() throws Exception { int servicePort = 8080; Service service = getExternalService(servicePort); Record record = KubernetesServiceImporter.createRecord(new JsonObject(mapper.writeValueAsString(service))); assertThat(record).isNotNull(); assertThat(record.getName()).isEqualTo("my-service"); assertThat(record.getMetadata().getString("kubernetes.name")).isEqualTo("my-service"); assertThat(record.getMetadata().getString("kubernetes.namespace")).isEqualTo("my-project"); assertThat(record.getMetadata().getString("kubernetes.uuid")).isEqualTo("uuid"); assertThat(record.getType()).isEqualTo(HttpEndpoint.TYPE); assertThat(record.getLocation().getString("host")).isEqualTo("my-external-service"); assertThat(record.getLocation().getInteger("port")).isEqualTo(servicePort); assertThat(record.getLocation().getBoolean("ssl")).isFalse(); assertThat(record.getLocation().getString("endpoint")).isEqualTo("http://my-external-service:" + servicePort); }
Example #12
Source File: KubernetesServerTest.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@Test public void testWatch() { AtomicBoolean done = new AtomicBoolean(); ServiceDiscovery discovery = ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions().setAutoRegistrationOfImporters(false)); discovery.registerServiceImporter(new KubernetesServiceImporter(), config().copy().put("namespace", "default"), ar -> done.set(ar.succeeded())); await().untilAtomic(done, is(true)); await().until(() -> { List<Record> records = getRecordsBlocking(discovery); try { assertThatListContains(records, "service3"); assertThatListDoesNotContain(records, "my-service"); assertThatListContains(records, "my-http-service"); return true; } catch (Throwable e) { return false; } }); }
Example #13
Source File: ConsulServiceImporterTest.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@Test public void testHttpImport() { services.add(buildService("172.17.0.2", "web", "web", new String[]{"rails", "http-endpoint"}, 80, "passing")); discovery = ServiceDiscovery.create(vertx); discovery.registerServiceImporter(new ConsulServiceImporter(), new JsonObject().put("host", "localhost").put("port", 5601)); await().until(() -> getAllRecordsBlocking().size() > 0); List<Record> list = getAllRecordsBlocking(); assertThat(list).hasSize(1); assertThat(list.get(0).getType()).isEqualTo(HttpEndpoint.TYPE); assertThat(list.get(0).getLocation().getString("endpoint")).isEqualTo("http://172.17.0.2:80"); }
Example #14
Source File: SchemaRegistrationTest.java From vertx-graphql-service-discovery with Apache License 2.0 | 6 votes |
@Before public void setUp() { vertx = Vertx.vertx(); options = new ServiceDiscoveryOptions().setName("theDiscovery") .setAnnounceAddress("theAnnounceAddress").setUsageAddress("theUsageAddress"); discovery = ServiceDiscovery.create(vertx, options); record = new Record() .setName("theRecord") .setType(Queryable.SERVICE_TYPE) .setMetadata(new JsonObject().put("publisherId", "thePublisherId")) .setLocation(new JsonObject().put(Record.ENDPOINT, Queryable.ADDRESS_PREFIX + ".DroidQueries")) .setStatus(Status.UP); definition = SchemaDefinition.createInstance(droidsSchema, SchemaMetadata.create(new JsonObject().put("publisherId", "thePublisherId"))); consumer = ProxyHelper.registerService(Queryable.class, vertx, definition, Queryable.ADDRESS_PREFIX + ".DroidQueries"); }
Example #15
Source File: RedisBackendService.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@Override public void remove(String uuid, Handler<AsyncResult<Record>> resultHandler) { Objects.requireNonNull(uuid, "No registration id in the record"); redis.send(cmd(HGET).arg(key).arg(uuid), ar -> { if (ar.succeeded()) { if (ar.result() != null) { redis.send(cmd(HDEL).arg(key).arg(uuid), deletion -> { if (deletion.succeeded()) { resultHandler.handle(Future.succeededFuture(new Record(new JsonObject(ar.result().toBuffer())))); } else { resultHandler.handle(Future.failedFuture(deletion.cause())); } }); } else { resultHandler.handle(Future.failedFuture("Record '" + uuid + "' not found")); } } else { resultHandler.handle(Future.failedFuture(ar.cause())); } }); }
Example #16
Source File: GraphQLServiceTest.java From vertx-graphql-service-discovery with Apache License 2.0 | 6 votes |
@Test public void should_Publish_Schema_Definition_With_Metadata(TestContext context) { Async async = context.async(); SchemaMetadata metadata = SchemaMetadata.create(new JsonObject() .put("someString", "someValue").put("someObject", new JsonObject())); GraphQLService.publish(vertx, discovery, starWarsSchema, options, metadata, rh -> { context.assertTrue(rh.succeeded()); Record record = rh.result().getRecord(); context.assertEquals("someValue", record.getMetadata().getString("someString")); context.assertEquals(new JsonObject(), record.getMetadata().getJsonObject("someObject")); // Check standard metadata that is added (for future use) JsonArray queries = record.getMetadata().getJsonArray(SchemaRegistration.METADATA_QUERIES); JsonArray mutations = record.getMetadata().getJsonArray(SchemaRegistration.METADATA_MUTATIONS); context.assertEquals(new JsonArray("[ \"hero\", \"human\" ]"), queries); context.assertEquals(new JsonArray(), mutations); async.complete(); }); }
Example #17
Source File: RecordCreationTest.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@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 #18
Source File: EventBusServiceJavaExamples.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
public void example1(ServiceDiscovery discovery) { Record record = EventBusService.createRecord( "some-eventbus-service", // The service name "address", // the service address, MyService.class // the service interface ); discovery.publish(record, ar -> { // ... }); }
Example #19
Source File: JDBCDataSource.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
/** * Convenient method that looks for a JDBC datasource source and provides the configured {@link io.vertx.ext.jdbc.JDBCClient}. The * async result is marked as failed is there are no matching services, or if the lookup fails. * * @param discovery The service discovery instance * @param filter The filter, must not be {@code null} * @param consumerConfiguration the consumer configuration * @param resultHandler the result handler */ static void getJDBCClient(ServiceDiscovery discovery, Function<Record, Boolean> filter, JsonObject consumerConfiguration, Handler<AsyncResult<JDBCClient>> resultHandler) { discovery.getRecord(filter, ar -> { if (ar.failed() || ar.result() == null) { resultHandler.handle(Future.failedFuture("No matching record")); } else { resultHandler.handle(Future.succeededFuture( discovery.<JDBCClient>getReferenceWithConfiguration(ar.result(), consumerConfiguration).get())); } }); }
Example #20
Source File: JDBCDataSourceTest.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@Test public void test() throws InterruptedException { JsonObject conf = new JsonObject() .put("driverclass", "org.hsqldb.jdbcDriver"); Record record = JDBCDataSource.createRecord("some-hsql-db", new JsonObject().put("url", "jdbc:hsqldb:file:target/dumb-db;shutdown=true"), new JsonObject().put("database", "some-raw-data")); discovery.publish(record, (r) -> { }); await().until(() -> record.getRegistration() != null); AtomicReference<Record> found = new AtomicReference<>(); discovery.getRecord(new JsonObject().put("name", "some-hsql-db"), ar -> { found.set(ar.result()); }); await().until(() -> found.get() != null); ServiceReference service = discovery.getReferenceWithConfiguration(found.get(), conf); JDBCClient client = service.get(); AtomicBoolean success = new AtomicBoolean(); client.getConnection(ar -> { if (ar.succeeded()) { ar.result().close(); } success.set(ar.succeeded()); }); await().untilAtomic(success, is(true)); service.release(); // Just there to be sure we can call it twice service.release(); }
Example #21
Source File: ZookeeperBackendService.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@Override public void store(Record record, Handler<AsyncResult<Record>> resultHandler) { if (record.getRegistration() != null) { resultHandler.handle(Future.failedFuture("The record has already been registered")); return; } String uuid = UUID.randomUUID().toString(); record.setRegistration(uuid); String content = record.toJson().encode(); Context context = Vertx.currentContext(); ensureConnected(x -> { if (x.failed()) { resultHandler.handle(Future.failedFuture(x.cause())); } else { try { client.create() .creatingParentsIfNeeded() .withMode(ephemeral ? CreateMode.EPHEMERAL : CreateMode.PERSISTENT) .inBackground((curatorFramework, curatorEvent) -> callback(context, record, resultHandler, curatorEvent)) .withUnhandledErrorListener((s, throwable) -> resultHandler.handle(Future.failedFuture(throwable))) .forPath(getPath(record.getRegistration()), content.getBytes(CHARSET)); } catch (Exception e) { resultHandler.handle(Future.failedFuture(e)); } } }); }
Example #22
Source File: KubernetesServiceImporter.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
private void unpublishRecord(Record record, Handler<Void> completionHandler) { publisher.unpublish(record.getRegistration(), ar -> { if (ar.failed()) { LOGGER.error("Cannot unregister kubernetes service", ar.cause()); } else { LOGGER.info("Kubernetes service unregistered from the vert.x registry: " + record.toJson()); if (completionHandler != null) { completionHandler.handle(null); } } }); }
Example #23
Source File: RedisDataSourceImpl.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@Override public ServiceReference get(Vertx vertx, ServiceDiscovery discovery, Record record, JsonObject configuration) { Objects.requireNonNull(vertx); Objects.requireNonNull(record); Objects.requireNonNull(discovery); return new RedisServiceReference(vertx, discovery, record, configuration); }
Example #24
Source File: ConsulBackendService.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@Override public void store(Record record, Handler<AsyncResult<Record>> resultHandler) { String uuid = UUID.randomUUID().toString(); if (record.getRegistration() != null) { throw new IllegalArgumentException("The record has already been registered"); } ServiceOptions serviceOptions = recordToServiceOptions(record, uuid); record.setRegistration(serviceOptions.getId()); Promise<Void> registration = Promise.promise(); client.registerService(serviceOptions, registration); registration.future().map(record).onComplete(resultHandler); }
Example #25
Source File: ConsulBackendService.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
private Future serviceToRecord(Service service) { //use the checks to set the record status Promise<CheckList> checkListFuture = Promise.promise(); client.healthChecks(service.getName(), checkListFuture); return checkListFuture.future().map(cl -> cl.getList().stream().map(Check::getStatus).allMatch(CheckStatus.PASSING::equals)) .map(st -> st ? new Record().setStatus(Status.UP) : new Record().setStatus(Status.DOWN)) .map(record -> { record.setMetadata(new JsonObject()); record.setLocation(new JsonObject()); record.setName(service.getName()); record.setRegistration(service.getId()); List<String> tags = service.getTags(); record.setType(ServiceType.UNKNOWN); ServiceTypes.all().forEachRemaining(type -> { if (service.getTags().contains(type.name())) { record.setType(type.name()); tags.remove(type.name()); } }); //retrieve the metadata object tags.stream().filter(t -> t.startsWith("metadata:")).map(s -> s.substring("metadata:".length())).map(JsonObject::new).forEach(json -> record.getMetadata().mergeIn(json)); //retrieve the location object tags.stream().filter(t -> t.startsWith("location:")).map(s -> s.substring("location:".length())).map(JsonObject::new).forEach(json -> record.getLocation().mergeIn(json)); record.getMetadata().put("tags", new JsonArray(tags.stream().filter(t -> !t.startsWith("metadata:") && !t.startsWith("location:")).collect(Collectors.toList()))); return record; }); }
Example #26
Source File: KubernetesServiceImporter.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
private void onChunk(JsonObject json) { String type = json.getString("type"); if (type == null) { return; } JsonObject service = json.getJsonObject("object"); switch (type) { case "ADDED": // new service Record record = createRecord(service); if (addRecordIfNotContained(record)) { LOGGER.info("Adding service " + record.getName()); publishRecord(record, null); } break; case "DELETED": case "ERROR": // remove service record = createRecord(service); LOGGER.info("Removing service " + record.getName()); Record storedRecord = removeRecordIfContained(record); if (storedRecord != null) { unpublishRecord(storedRecord, null); } break; case "MODIFIED": record = createRecord(service); LOGGER.info("Modifying service " + record.getName()); storedRecord = replaceRecordIfContained(record); if (storedRecord != null) { unpublishRecord(storedRecord, x -> publishRecord(record, null)); } } }
Example #27
Source File: ConsulBackendService.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@Override public void remove(Record record, Handler<AsyncResult<Record>> resultHandler) { Objects.requireNonNull(record.getRegistration(), "No registration id in the record"); Promise<Void> deregistration = Promise.promise(); client.deregisterService(record.getRegistration(), deregistration); deregistration.future().map(record).onComplete(resultHandler); }
Example #28
Source File: ServiceTypesTest.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@Test(expected = IllegalArgumentException.class) public void notAKnownType() { Record record = new Record(); record.setType("bob"); ServiceTypes.get(record); }
Example #29
Source File: MessageSourceExamples.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
public void example1(ServiceDiscovery discovery) { Record record1 = MessageSource.createRecord( "some-message-source-service", // The service name "some-address", // The event bus address JsonObject.class // The message payload type ); Record record2 = MessageSource.createRecord( "some-other-message-source-service", // The service name "some-address", // The event bus address JsonObject.class, // The message payload type new JsonObject().put("some-metadata", "some value") ); }
Example #30
Source File: KubernetesServiceImporter.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
private Record removeRecordIfContained(Record record) { for (Record rec : records) { if (areTheSameService(rec, record)) { records.remove(rec); return rec; } } return null; }