io.vertx.serviceproxy.ProxyHelper Java Examples

The following examples show how to use io.vertx.serviceproxy.ProxyHelper. 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: PortfolioVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {

  ServiceDiscovery.create(vertx, discovery -> {
    this.discovery = discovery;
    // Create the service object
    PortfolioServiceImpl service = new PortfolioServiceImpl(vertx, discovery, config().getDouble("money", 10000.00));

    // Register the service proxy on the event bus
    ProxyHelper.registerService(PortfolioService.class, vertx.getDelegate(), service, ADDRESS);

    Record record = EventBusService.createRecord("portfolio", ADDRESS, PortfolioService.class.getName());
    discovery.publish(record, ar -> {
      if (ar.succeeded()) {
        this.record = record;
        System.out.println("Portfolio service published");

        // Used for health check
        vertx.createHttpServer().requestHandler(req -> req.response().end("OK")).listen(8080);
      } else {
        ar.cause().printStackTrace();
      }
    });

  });
}
 
Example #2
Source File: CartVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();

  // create the service instance
  this.shoppingCartService = new ShoppingCartServiceImpl(vertx, discovery, config());
  this.checkoutService = CheckoutService.createService(vertx, discovery);
  // register the service proxy on event bus
  ProxyHelper.registerService(CheckoutService.class, vertx, checkoutService, CheckoutService.SERVICE_ADDRESS);
  ProxyHelper.registerService(ShoppingCartService.class, vertx, shoppingCartService, ShoppingCartService.SERVICE_ADDRESS);

  // publish the service in the discovery infrastructure
  publishEventBusService(CheckoutService.SERVICE_NAME, CheckoutService.SERVICE_ADDRESS, CheckoutService.class)
    .compose(servicePublished ->
      publishEventBusService(ShoppingCartService.SERVICE_NAME, ShoppingCartService.SERVICE_ADDRESS, ShoppingCartService.class))
    .compose(servicePublished ->
      publishMessageSource("shopping-payment-message-source", CheckoutService.PAYMENT_EVENT_ADDRESS))
    .compose(sourcePublished ->
      publishMessageSource("shopping-order-message-source", CheckoutService.ORDER_EVENT_ADDRESS))
    .compose(sourcePublished -> deployRestVerticle())
    .setHandler(future.completer());
}
 
Example #3
Source File: KueVerticle.java    From vertx-kue with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  this.config = config();
  this.jobService = JobService.create(vertx, config);
  // create redis client
  RedisClient redisClient = RedisHelper.client(vertx, config);
  redisClient.ping(pr -> { // test connection
    if (pr.succeeded()) {
      logger.info("Kue Verticle is running...");

      // register job service
      ProxyHelper.registerService(JobService.class, vertx, jobService, EB_JOB_SERVICE_ADDRESS);

      future.complete();
    } else {
      logger.error("oops!", pr.cause());
      future.fail(pr.cause());
    }
  });
}
 
Example #4
Source File: PortfolioVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {

  ServiceDiscovery.create(vertx, discovery -> {
    this.discovery = discovery;
    // Create the service object
    PortfolioServiceImpl service = new PortfolioServiceImpl(vertx, discovery, config().getDouble("money", 10000.00));

    // Register the service proxy on the event bus
    ProxyHelper.registerService(PortfolioService.class, vertx.getDelegate(), service, ADDRESS);

    Record record = EventBusService.createRecord("portfolio", ADDRESS, PortfolioService.class.getName());
    discovery.publish(record, ar -> {
      if (ar.succeeded()) {
        this.record = record;
        System.out.println("Portfolio service published");

        // Used for health check
        vertx.createHttpServer().requestHandler(req -> req.response().end("OK")).listen(8080);
      } else {
        ar.cause().printStackTrace();
      }
    });

  });
}
 
Example #5
Source File: ServiceDiscoveryRestEndpointTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateWithUUIDMismatch() throws UnsupportedEncodingException {
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");
  Record record = new Record()
    .setName("Hello")
    .setLocation(new JsonObject().put(Record.ENDPOINT, "address"));

  discovery.publish(record, (r) -> {
  });
  await().until(() -> record.getRegistration() != null);

  Record retrieved = retrieve(record.getRegistration());
  assertThat(retrieved.getStatus()).isEqualTo(Status.UP);

  retrieved.setStatus(Status.OUT_OF_SERVICE).setRegistration("not-the-right-one").getMetadata().put("foo", "bar");

  Restafari.Response response = given().body(retrieved.toJson().toString())
    .put("/discovery/" + record.getRegistration());
  assertThat(response.getStatusCode()).isEqualTo(400);
}
 
Example #6
Source File: ServiceDiscoveryRestEndpointTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetrievingMissingRecord() {
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");
  Record record = new Record()
    .setName("Hello")
    .setLocation(new JsonObject().put(Record.ENDPOINT, "address"));

  discovery.publish(record, (r) -> {
  });
  await().until(() -> record.getRegistration() != null);

  Record retrieved = retrieve(record.getRegistration());
  assertThat(retrieved.getStatus()).isEqualTo(Status.UP);

  // Unregister it
  Restafari.Response response2 = delete("/discovery/" + record.getRegistration());
  assertThat(response2.getStatusCode()).isEqualTo(204);

  Restafari.Response response = get("/discovery/" + record.getRegistration());
  assertThat(response.getStatusCode()).isEqualTo(404);
}
 
Example #7
Source File: ServiceDiscoveryRestEndpointTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void testLookupWithNonMatchingQuery() throws UnsupportedEncodingException {
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");

  Record record1 = EventBusService.createRecord("Hello", "address", HelloService.class,
    new JsonObject().put("key", "foo"));
  Record record2 = EventBusService.createRecord("Hello-2", "address", HelloService.class,
    new JsonObject().put("key", "bar"));

  discovery.publish(record1, (r) -> {
  });
  discovery.publish(record2, (r) -> {
  });

  await().until(() -> record1.getRegistration() != null);
  await().until(() -> record2.getRegistration() != null);

  JsonArray services = given()
    .param("query", "{\"stuff\":\"*\"}")
    .get("/discovery")
    .asJsonArray();

  assertThat(services.size()).isEqualTo(0);
}
 
Example #8
Source File: SchemaRegistrationTest.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: PortfolioVerticle.java    From vertx-microservices-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
  super.start();

  // Create the service object
  PortfolioServiceImpl service = new PortfolioServiceImpl(vertx, discovery, config().getDouble("money", 10000.00));

  // Register the service proxy on the event bus
  ProxyHelper.registerService(PortfolioService.class, vertx, service, ADDRESS);

  // Publish it in the discovery infrastructure
  publishEventBusService("portfolio", ADDRESS, PortfolioService.class, ar -> {
    if (ar.failed()) {
      ar.cause().printStackTrace();
    } else {
      System.out.println("Portfolio service published : " + ar.succeeded());
    }
  });

  // TODO
  //----

  //----
}
 
Example #10
Source File: PortfolioServiceImplTest.java    From vertx-microservices-workshop with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp(TestContext tc) {
  vertx = Vertx.vertx();

  Async async = tc.async();
  vertx.deployVerticle(PortfolioVerticle.class.getName(), id -> {
    service = ProxyHelper.createProxy(PortfolioService.class, vertx, PortfolioService.ADDRESS);
    service.getPortfolio(ar -> {
      if (!ar.succeeded()) {
        System.out.println(ar.cause());
      }
      tc.assertTrue(ar.succeeded());
      original = ar.result();
      async.complete();
    });
  });
}
 
Example #11
Source File: PortfolioVerticle.java    From vertx-microservices-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
  super.start();

  // Create the service object
  PortfolioServiceImpl service = new PortfolioServiceImpl(vertx, discovery, config().getDouble("money", 10000.00));

  // Register the service proxy on the event bus
  ProxyHelper.registerService(PortfolioService.class, vertx, service, ADDRESS);

  // Publish it in the discovery infrastructure
  publishEventBusService("portfolio", ADDRESS, PortfolioService.class, ar -> {
    if (ar.failed()) {
      ar.cause().printStackTrace();
    } else {
      System.out.println("Portfolio service published : " + ar.succeeded());
    }
  });

  //----
  // The portfolio event service
  publishMessageSource("portfolio-events", EVENT_ADDRESS, ar -> {
    if (ar.failed()) {
      ar.cause().printStackTrace();
    } else {
      System.out.println("Portfolio Events service published : " + ar.succeeded());
    }
  });
  //----
}
 
Example #12
Source File: GraphQLService.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
/**
 * Publish a GraphQL schema for querying.
 * <p>
 * On success a {@link SchemaRegistration} is returned. It contains the message consumer of the
 * {@link Queryable} service proxy that supplies the published {@link SchemaDefinition}, the published service
 * discovery record, and the {@link ServiceDiscovery} it was published to.
 * <p>
 * Note that unless invoked from a {@link SchemaPublisher} a
 * client needs to keep hold of the returned {@link Record} as long as it is published.
 *
 * @param vertx         the vert.x instance
 * @param discovery     the service discovery instance
 * @param definition    the service proxy instance exposing the graphql schema
 * @param resultHandler the result handler that returns the registration
 */
static void publish(Vertx vertx, ServiceDiscovery discovery, SchemaDefinition definition,
                    Handler<AsyncResult<SchemaRegistration>> resultHandler) {

    Objects.requireNonNull(vertx, "Vertx cannot be null");
    Objects.requireNonNull(discovery, "Service discovery cannot be null");
    Objects.requireNonNull(definition, "GraphQL queryable cannot be null");
    Objects.requireNonNull(resultHandler, "Publication result handler cannot be null");

    // TODO Caching proxy ok?

    final MessageConsumer<JsonObject> serviceConsumer;
    if (definition.metadata().get("publisherId") == null) {
        serviceConsumer = ProxyHelper.registerService(
                Queryable.class, vertx, definition, definition.serviceAddress());
    } else {
        // Publisher handles service instantiation, manages consumer.
        serviceConsumer = null;
    }

    Record record = new Record()
            .setType(SERVICE_TYPE)
            .setName(definition.schemaName())
            .setMetadata(definition.metadata().toJson())
            .setLocation(new JsonObject().put(Record.ENDPOINT, definition.serviceAddress()));

    discovery.publish(record, rh -> {
        if (rh.succeeded()) {
            resultHandler.handle(Future.succeededFuture(
                    SchemaRegistration.create(discovery, null, rh.result(), definition, serviceConsumer)));
        } else {
            resultHandler.handle(Future.failedFuture(rh.cause()));
        }
    });
}
 
Example #13
Source File: SchemaMessageConsumers.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
public <T extends Queryable> MessageConsumer<JsonObject> registerServiceConsumer(String address, T implementation) {
    MessageConsumer<JsonObject> serviceConsumer;
    if (!messageConsumers.containsKey(address)) {
        serviceConsumer = ProxyHelper.registerService(Queryable.class, vertx, implementation, address);
        messageConsumers.put(address, serviceConsumer);
    } else {
        serviceConsumer = messageConsumers.get(address);
    }
    consumerRegistrations.add(address);
    return serviceConsumer;
}
 
Example #14
Source File: PortfolioVerticleTest.java    From vertx-microservices-workshop with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceAccess() {
  Vertx vertx = Vertx.vertx();
  vertx.deployVerticle(PortfolioVerticle.class.getName());

  PortfolioService proxy = ProxyHelper.createProxy(PortfolioService.class, vertx, PortfolioService.ADDRESS);

  assertThat(proxy).isNotNull();
  AtomicReference<Portfolio> reference = new AtomicReference<>();
  proxy.getPortfolio(ar -> reference.set(ar.result()));

  await().untilAtomic(reference, not(nullValue()));

  vertx.close();
}
 
Example #15
Source File: ServiceProxyInvocationHandler.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param vertx
 * @param executor
 * @param serviceInterface
 * @param address
 */
ServiceProxyInvocationHandler(ServiceProxySupport serviceProxySupport, Class<?> serviceInterface, String address) {
    this.executor = serviceProxySupport.getExecutor();
    DeliveryOptions deliveryOptions = serviceProxySupport.getDefaultDeliveryOptions(serviceInterface);
    if (deliveryOptions != null) {
        this.delegate = ProxyHelper.createProxy(serviceInterface, serviceProxySupport.getVertx(), address, deliveryOptions);
    } else {
        this.delegate = ProxyHelper.createProxy(serviceInterface, serviceProxySupport.getVertx(), address);
    }
    this.handlerParamPositionCache = new ConcurrentHashMap<>();
}
 
Example #16
Source File: ServiceProxiesTest.java    From vertx-lang-groovy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithGroovyConsumer() {
  // Step 1 - register the service
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");
  Record record = EventBusService.createRecord("Hello", "address", HelloService.class);

  discovery.publish(record, (r) -> {
  });
  await().until(() -> record.getRegistration() != null);

  // Step 2 - register a consumer that get the result
  AtomicReference<JsonObject> result = new AtomicReference<>();
  vertx.eventBus().<JsonObject>consumer("result", message -> result.set(message.body()));

  // Step 3 - deploy the verticle
  vertx.deployVerticle("discovery/verticles/HelloServiceConsumer.groovy", ar -> {
    if (ar.failed()) {
      // Will fail anyway.
      ar.cause().printStackTrace();
    }
  });

  await().until(() -> result.get() != null);

  assertThat(result.get().getString("status")).isEqualTo("ok");
  assertThat(result.get().getString("message")).isEqualTo("stuff vert.x");
}
 
Example #17
Source File: UserAccountVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();

  // create the service instance
  accountService = new JdbcAccountServiceImpl(vertx, config());
  // register the service proxy on event bus
  ProxyHelper.registerService(AccountService.class, vertx, accountService, SERVICE_ADDRESS);
  // publish the service and REST endpoint in the discovery infrastructure
  publishEventBusService(SERVICE_NAME, SERVICE_ADDRESS, AccountService.class)
    .compose(servicePublished -> deployRestVerticle())
    .setHandler(future.completer());
}
 
Example #18
Source File: ServiceProxiesTest.java    From vertx-lang-groovy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithGroovyConsumerWithJsonFilter() {
  // Step 1 - register the service
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");
  Record record = EventBusService.createRecord("Hello", "address", HelloService.class);

  discovery.publish(record, (r) -> {
  });
  await().until(() -> record.getRegistration() != null);

  // Step 2 - register a consumer that get the result
  AtomicReference<JsonObject> result = new AtomicReference<>();
  vertx.eventBus().<JsonObject>consumer("result", message -> result.set(message.body()));

  // Step 3 - deploy the verticle
  vertx.deployVerticle("discovery/verticles/HelloServiceConsumerWithJsonFilter.groovy", ar -> {
    if (ar.failed()) {
      // Will fail anyway.
      ar.cause().printStackTrace();
    }
  });

  await().until(() -> result.get() != null);

  assertThat(result.get().getString("status")).isEqualTo("ok");
  assertThat(result.get().getString("message")).isEqualTo("stuff vert.x");
}
 
Example #19
Source File: ProductVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();

  // create the service instance
  ProductService productService = new ProductServiceImpl(vertx, config());
  // register the service proxy on event bus
  ProxyHelper.registerService(ProductService.class, vertx, productService, SERVICE_ADDRESS);
  // publish the service in the discovery infrastructure
  initProductDatabase(productService)
    .compose(databaseOkay -> publishEventBusService(ProductService.SERVICE_NAME, SERVICE_ADDRESS, ProductService.class))
    .compose(servicePublished -> deployRestService(productService))
    .setHandler(future.completer());
}
 
Example #20
Source File: OrderVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();
  this.orderService = new OrderServiceImpl(vertx, config());
  ProxyHelper.registerService(OrderService.class, vertx, orderService, SERVICE_ADDRESS);

  initOrderDatabase()
    .compose(databaseOkay -> publishEventBusService(SERVICE_NAME, SERVICE_ADDRESS, OrderService.class))
    .compose(servicePublished -> prepareDispatcher())
    .compose(dispatcherPrepared -> deployRestVerticle())
    .setHandler(future.completer());
}
 
Example #21
Source File: CacheComponentVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();

  // create the service instance
  CounterService counterService = new DefaultCounterServiceImpl(vertx, config());
  // register the service proxy on event bus
  ProxyHelper.registerService(CounterService.class, vertx, counterService, CounterService.SERVICE_ADDRESS);
  // publish the service in the discovery infrastructure
  publishEventBusService(CounterService.SERVICE_NAME, CounterService.SERVICE_ADDRESS, CounterService.class)
    .setHandler(future.completer());
}
 
Example #22
Source File: ServiceDiscoveryTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithRXConsumer() {
  // Step 1 - register the service
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");
  Record record = EventBusService.createRecord("Hello", "address", HelloService.class);

  discovery.publish(record, (r) -> {
  });
  await().until(() -> record.getRegistration() != null);

  // Step 2 - register a consumer that get the result
  AtomicReference<JsonObject> result = new AtomicReference<>();
  vertx.eventBus().<JsonObject>consumer("result", message -> result.set(message.body()));

  // Step 3 - deploy the verticle
  vertx.deployVerticle(RXHelloServiceConsumer.class.getName(), ar -> {
    if (ar.failed()) {
      // Will fail anyway.
      ar.cause().printStackTrace();
    }
  });

  await().until(() -> result.get() != null);

  assertThat(result.get().getString("status")).isEqualTo("ok");
  assertThat(result.get().getString("message")).isEqualTo("stuff vert.x");
}
 
Example #23
Source File: StoreVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();

  crudService = new StoreCRUDServiceImpl(vertx, config());
  ProxyHelper.registerService(StoreCRUDService.class, vertx, crudService, SERVICE_ADDRESS);
  // publish service and deploy REST verticle
  publishEventBusService(SERVICE_NAME, SERVICE_ADDRESS, StoreCRUDService.class)
    .compose(servicePublished -> deployRestVerticle(crudService))
    .setHandler(future.completer());
}
 
Example #24
Source File: ServiceDiscoveryRestEndpointTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatWeGetTheTwoPublishedServicesWithMetadata() {
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");

  Record record1 = EventBusService.createRecord("Hello", "address", HelloService.class,
    new JsonObject().put("key", "foo"));
  Record record2 = EventBusService.createRecord("Hello-2", "address", HelloService.class,
    new JsonObject().put("key", "bar"));

  discovery.publish(record1, (r) -> {
  });
  discovery.publish(record2, (r) -> {
  });

  await().until(() -> record1.getRegistration() != null);
  await().until(() -> record2.getRegistration() != null);

  Restafari.Response response = get("/discovery");
  JsonArray services = new JsonArray(response.asString());

  assertThat(services.size()).isEqualTo(2);

  for (Object json : services) {
    Record rec = new Record((JsonObject) json);
    assertThat(rec.getStatus()).isEqualTo(Status.UP);
    assertThat(rec.getRegistration()).isNotNull();
    assertThat(rec.getName()).startsWith("Hello");
    assertThat(rec.getMetadata().getString("key")).isNotNull();

    get("/discovery/" + rec.getRegistration()).then().body("name", not(nullValue()));
  }
}
 
Example #25
Source File: PortfolioVerticleTest.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceAccess() {
  Vertx vertx = Vertx.vertx();
  vertx.deployVerticle(PortfolioVerticle.class.getName());

  PortfolioService proxy = ProxyHelper.createProxy(PortfolioService.class, vertx, PortfolioService.ADDRESS);

  assertThat(proxy).isNotNull();
  AtomicReference<Portfolio> reference = new AtomicReference<>();
  proxy.getPortfolio(ar -> reference.set(ar.result()));

  await().untilAtomic(reference, not(nullValue()));

  vertx.close();
}
 
Example #26
Source File: DiscoveryImplTestBase.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnounce() {
  List<Record> announces = new ArrayList<>();

  vertx.eventBus().consumer(ServiceDiscoveryOptions.DEFAULT_ANNOUNCE_ADDRESS,
    msg -> announces.add(new Record((JsonObject) msg.body())));

  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");
  Record record = new Record()
    .setName("Hello")
    .setMetadata(new JsonObject().put("key", "A"))
    .setLocation(new JsonObject().put(Record.ENDPOINT, "address"));
  Record record2 = new Record()
    .setName("Hello-2")
    .setMetadata(new JsonObject().put("key", "B"))
    .setLocation(new JsonObject().put(Record.ENDPOINT, "address2"));
  discovery.publish(record, (r) -> {
  });
  discovery.publish(record2, (r) -> {
  });
  await().until(() -> record.getRegistration() != null);
  await().until(() -> record2.getRegistration() != null);

  await().until(() -> announces.size() == 2);
  for (Record rec : announces) {
    assertThat(rec.getStatus()).isEqualTo(Status.UP);
  }

  discovery.unpublish(record2.getRegistration(), v -> {

  });

  await().until(() -> announces.size() == 3);
  assertThat(announces.get(2).getStatus()).isEqualTo(Status.DOWN);
}
 
Example #27
Source File: ServiceDiscoveryRestEndpointTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdate() throws UnsupportedEncodingException {
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");
  Record record = new Record()
    .setName("Hello")
    .setLocation(new JsonObject().put(Record.ENDPOINT, "address"));

  discovery.publish(record, (r) -> {
  });
  await().until(() -> record.getRegistration() != null);

  Record retrieved = retrieve(record.getRegistration());
  assertThat(retrieved.getStatus()).isEqualTo(Status.UP);

  retrieved.setStatus(Status.OUT_OF_SERVICE).getMetadata().put("foo", "bar");

  Restafari.Response response = given().body(retrieved.toJson().toString())
    .put("/discovery/" + record.getRegistration());
  assertThat(response.getStatusCode()).isEqualTo(200);
  retrieved = new Record(new JsonObject(response.asString()));

  assertThat(retrieved.getStatus()).isEqualTo(Status.OUT_OF_SERVICE);
  assertThat(retrieved.getMetadata().getString("foo")).isEqualTo("bar");

  // Check that we cannot find the service without specifying the Status
  response = get("/discovery/");
  JsonArray services = new JsonArray(response.asString());
  assertThat(services.size()).isEqualTo(0);

  services = given()
    .param("query", "{\"status\":\"*\"}")
    .get("/discovery")
    .asJsonArray();

  assertThat(services.size()).isEqualTo(1);
}
 
Example #28
Source File: PortfolioServiceImplTest.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext tc) {
  vertx = Vertx.vertx();

  Async async = tc.async();
  vertx.deployVerticle(io.vertx.workshop.portfolio.impl.PortfolioVerticle.class.getName(), id -> {
    service = ProxyHelper.createProxy(PortfolioService.class, vertx, PortfolioService.ADDRESS);
    service.getPortfolio(ar -> {
      tc.assertTrue(ar.succeeded());
      original = ar.result();
      async.complete();
    });
  });
}
 
Example #29
Source File: PortfolioVerticle.java    From microtrader with MIT License 5 votes vote down vote up
@Override
public void start() {
    super.start();

    // Create the service object
    PortfolioServiceImpl service = new PortfolioServiceImpl(vertx, discovery, config().getDouble("money", 10000.00));

    // Register the service proxy on the event bus
    ProxyHelper.registerService(PortfolioService.class, vertx, service, ADDRESS);

    // Publish it in the discovery infrastructure
    publishEventBusService("portfolio", ADDRESS, PortfolioService.class, ar -> {
        if (ar.failed()) {
            ar.cause().printStackTrace();
        } else {
            System.out.println("Portfolio service published : " + ar.succeeded());
        }
    });

    publishMessageSource("portfolio-events", EVENT_ADDRESS, ar -> {
        if (ar.failed()) {
            ar.cause().printStackTrace();
        } else {
            System.out.println("Portfolio Events service published : " + ar.succeeded());
        }
    });

    // Java traders
    vertx.deployVerticle(CompulsiveTraderVerticle.class.getName(), new DeploymentOptions().setInstances(3));
}
 
Example #30
Source File: ServiceDiscoveryRestEndpointTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testLookupWithQuery() throws UnsupportedEncodingException {
  HelloService svc = new HelloServiceImpl("stuff");
  ProxyHelper.registerService(HelloService.class, vertx, svc, "address");

  Record record1 = EventBusService.createRecord("Hello", "address", HelloService.class,
    new JsonObject().put("key", "foo"));
  Record record2 = EventBusService.createRecord("Hello-2", "address", HelloService.class,
    new JsonObject().put("key", "bar"));

  discovery.publish(record1, (r) -> {
  });
  discovery.publish(record2, (r) -> {
  });

  await().until(() -> record1.getRegistration() != null);
  await().until(() -> record2.getRegistration() != null);


  JsonArray services =
    given()
      .param("query", "{\"name\":\"Hello\"}")
      .get("/discovery")
      .asJsonArray();

  assertThat(services.size()).isEqualTo(1);
}