io.vertx.reactivex.servicediscovery.ServiceDiscovery Java Examples

The following examples show how to use io.vertx.reactivex.servicediscovery.ServiceDiscovery. 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: CurrencyServiceProxy.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    Router router = Router.router(vertx);
    router.get().handler(this::convertPortfolioToEuro);
    router.post().handler(BodyHandler.create());
    router.post().handler(this::delegateWithCircuitBreaker);

    circuit = CircuitBreaker.create("circuit-breaker", vertx,
        new CircuitBreakerOptions()
            .setFallbackOnFailure(true)
            .setMaxFailures(3)
            .setResetTimeout(5000)
            .setTimeout(1000)
    );

    discovery = ServiceDiscovery.create(vertx);


    vertx.createHttpServer()
        .requestHandler(router::accept)
        .listen(8080);
}
 
Example #2
Source File: CurrencyServiceProxy.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    Router router = Router.router(vertx);
    router.get().handler(this::convertPortfolioToEuro);
    router.post().handler(BodyHandler.create());
    router.post().handler(this::delegateWithCircuitBreaker);

    circuit = CircuitBreaker.create("circuit-breaker", vertx,
        new CircuitBreakerOptions()
            .setFallbackOnFailure(true)
            .setMaxFailures(3)
            .setResetTimeout(5000)
            .setTimeout(1000)
    );

    discovery = ServiceDiscovery.create(vertx);


    vertx.createHttpServer()
        .requestHandler(router::accept)
        .listen(8080);
}
 
Example #3
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 #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: DiscoveryWebClientInjector.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
public Single<WebClient> resolve(Class<? extends Single<WebClient>> rawType, Type genericType, Annotation[] annotations) {
	ServiceDiscovery discovery = AppGlobals.get().getGlobal(ServiceDiscovery.class);
	for (Annotation annotation : annotations) {
		if(annotation.annotationType() == ServiceName.class) {
			String serviceName = ((ServiceName) annotation).value();
			// FIXME: release client
			return discovery.rxGetRecord(record -> record.getName().equals(serviceName))
					.map(record -> discovery.getReference(record).getAs(WebClient.class));
		}
	}
	return null;
}
 
Example #6
Source File: MyRX2Verticle.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
private synchronized JsonArray getBindings(ServiceDiscovery discovery) {
  JsonArray array = new JsonArray();
  for (ServiceReference ref : discovery.bindings()) {
    array.add(ref.toString());
  }
  return array;
}
 
Example #7
Source File: GeneratorConfigVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called when the verticle is deployed.
 */
@Override
public void start(Future<Void> future) {
    discovery = ServiceDiscovery.create(vertx);
    ConfigRetriever retriever = ConfigRetriever.create(vertx, getConfigurationOptions());

    retriever.rxGetConfig()
        // Read the configuration, and deploy a MarketDataVerticle for each company listed in the configuration.
        .flatMap(config ->
            Observable.fromIterable(config.getJsonArray("companies"))
                .cast(JsonObject.class)
                // Deploy the verticle with a configuration.
                .flatMapSingle(company -> vertx.rxDeployVerticle(MarketDataVerticle.class.getName(),
                    new DeploymentOptions().setConfig(company)))
                .toList()
        )
        // Deploy another verticle
        .flatMap(l -> vertx.rxDeployVerticle(RestQuoteAPIVerticle.class.getName()))
        // Expose the market-data message source
        .flatMap(x -> discovery.rxPublish(MessageSource.createRecord("market-data", ADDRESS)))
        .subscribe((rec, err) -> {
            if (rec != null) {
                this.record = rec;
                future.complete();
            } else {
                future.fail(err);
            }
        });
}
 
Example #8
Source File: GeneratorConfigVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called when the verticle is deployed.
 */
@Override
public void start(Future<Void> future) {
    discovery = ServiceDiscovery.create(vertx);
    ConfigRetriever retriever = ConfigRetriever.create(vertx, getConfigurationOptions());

    retriever.rxGetConfig()
        // Read the configuration, and deploy a MarketDataVerticle for each company listed in the configuration.
        .flatMap(config ->
            Observable.fromIterable(config.getJsonArray("companies"))
                .cast(JsonObject.class)
                // Deploy the verticle with a configuration.
                .flatMapSingle(company -> vertx.rxDeployVerticle(MarketDataVerticle.class.getName(),
                    new DeploymentOptions().setConfig(company)))
                .toList()
        )
        // Deploy another verticle
        .flatMap(l -> vertx.rxDeployVerticle(RestQuoteAPIVerticle.class.getName()))
        // Expose the market-data message source
        .flatMap(x -> discovery.rxPublish(MessageSource.createRecord("market-data", ADDRESS)))
        .subscribe((rec, err) -> {
            if (rec != null) {
                this.record = rec;
                future.complete();
            } else {
                future.fail(err);
            }
        });
}
 
Example #9
Source File: Exercise3Verticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
    ServiceDiscovery discovery = ServiceDiscovery.create(vertx);

    // 1 - Get the Web Client using the `HttpEndpoint.rxGetWebClient` method. Use the same lambda as in the
    // previous exercise.
    // 2 - Invoke the HTTP service as in the previous exercise
    // 3 - Extract the body as String
    // 4 - Subscribe and display the result on the console
    // TODO
   
}
 
Example #10
Source File: Exercise2Verticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
    discovery = ServiceDiscovery.create(vertx);

    // 1 - Get the service record using `rxGetRecord`. Pass the lambda `svc -> svc.getName().equals("greetings")` as
    // parameter to retrieve the service with the name "greetings"
    // 2 - With the record (`.map`), get the service reference using `discovery.getReference`
    // 3 - With the reference (`.map`), get a WebClient (Vert.x http client) using `ref.getAs(WebClient.class)`
    // 4 - With the client (`.flatMapSingle`), invoke the service using: `client.get("/greetings/vert.x-low-level-api").rxSend()`
    // 5 - With the response (`.map`), extract the body as string (`bodyAsString` method)
    // 6 - Finally subscribe and print the result on the console
    // TODO
   
}
 
Example #11
Source File: Exercise1Verticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
    // Create a simple HTTP service (using Vert.x Web Router) and publish it in the service discovery.
    // As we want to complete the deployment when the service is exposed (asynchronous operation), we use a
    // `Future` argument to indicate when the deployment is completed. This allows deploying the other verticle
    // after the deployment completion of this one.


    // Create an instance of service discovery
    this.discovery = ServiceDiscovery.create(vertx);

    // Simple HTTP API using Vert.x Web Router.
    Router router = Router.router(vertx);
    router.get("/").handler(rc -> rc.response().end("OK"));
    router.get("/greetings").handler(rc -> rc.response().end("Hello world"));
    router.get("/greetings/:name").handler(rc -> rc.response().end("Hello " + rc.pathParam("name")));

    
    vertx.createHttpServer()
        .requestHandler(router::accept)
        .rxListen(8080)
        // When the server is ready, we publish the service
        .flatMap(this::publish)
        // Store the record, required to un-publish it
        .doOnSuccess(rec -> this.record = rec)
        .toCompletable()
        .subscribe(toObserver(future));
}
 
Example #12
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the verticle asynchronously. The the initialization is completed, it calls
 * `complete()` on the given {@link Future} object. If something wrong happens,
 * `fail` is called.
 *
 * @param future the future to indicate the completion
 */
@Override
public void start(Future<Void> future) {
    // creates the jdbc client.

    ServiceDiscovery.create(vertx, discovery -> {

        // Discover and configure the database.
        Single<JDBCClient> jdbc = JDBCDataSource.rxGetJDBCClient(discovery,
            svc -> svc.getName().equals("audit-database"),
            getDatabaseConfiguration()
        ).doOnSuccess(jdbcClient -> this.jdbc = jdbcClient);

        // TODO
        // ----

        Single<JDBCClient> databaseReady = jdbc
            .flatMap(client -> initializeDatabase(client, true));
        Single<HttpServer> httpServerReady = configureTheHTTPServer();
        Single<MessageConsumer<JsonObject>> messageConsumerReady = retrieveThePortfolioMessageSource();

        Single<MessageConsumer<JsonObject>> readySingle = Single.zip(databaseReady, httpServerReady,
            messageConsumerReady, (db, http, consumer) -> consumer);

        // ----

        // signal a verticle start failure
        readySingle.doOnSuccess(consumer -> {
            // on success we set the handler that will store message in the database
            consumer.handler(message -> storeInDatabase(message.body()));
        }).subscribe(consumer -> {
            // complete the verticle start with a success
            future.complete();
            ready = true;
        }, future::fail);
    });


}
 
Example #13
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the verticle asynchronously. The the initialization is completed, it calls
 * `complete()` on the given {@link Future} object. If something wrong happens,
 * `fail` is called.
 *
 * @param future the future to indicate the completion
 */
@Override
public void start(Future<Void> future) {
    // creates the jdbc client.

    ServiceDiscovery.create(vertx, discovery -> {

        // Discover and configure the database.
        Single<JDBCClient> jdbc = JDBCDataSource.rxGetJDBCClient(discovery,
            svc -> svc.getName().equals("audit-database"),
            getDatabaseConfiguration()
        ).doOnSuccess(jdbcClient -> this.jdbc = jdbcClient);

        // TODO
        // ----

        Single<MessageConsumer<JsonObject>> readySingle = Single
            .error(new UnsupportedOperationException("Not implemented yet"));

        // ----

        // signal a verticle start failure
        readySingle.doOnSuccess(consumer -> {
            // on success we set the handler that will store message in the database
            consumer.handler(message -> storeInDatabase(message.body()));
        }).subscribe(consumer -> {
            // complete the verticle start with a success
            future.complete();
            // indicate our readiness state
            ready = true;
        }, future::fail);
    });


}
 
Example #14
Source File: RXCompulsiveTraderVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) {
    String company = TraderUtils.pickACompany();
    int numberOfShares = TraderUtils.pickANumber();
    System.out.println("Java-RX compulsive trader configured for company " + company + " and shares: " +
        numberOfShares);


    ServiceDiscovery.create(vertx, discovery -> {
        Single<PortfolioService> retrieveThePortfolioService = RXEventBusService.rxGetProxy(discovery, PortfolioService.class,
            rec -> rec.getName().equalsIgnoreCase("portfolio"));

        Single<MessageConsumer<JsonObject>> retrieveTheMarket = MessageSource.rxGetConsumer(discovery,
            rec -> rec.getName().equalsIgnoreCase("market-data"));

        //TODO
        //----

        // TODO 1 - "wait" for both single to be completed (using Single.zip or Single.zipWith methods)

        // TODO 2 - When both single have completed, attach the handler to the message consumer to execute the
        // trading logic

        // TODO 3 - Use the TraderUtils.drumpTradingLogic method returning a Completable. Don't forget to
        // subscribe to it, or nothing will happen. Return "true" to comply with the "zip" operator
        // signature.


        // TODO 4 - Transform the output into a Completable (toCompletable) and subscribe to it using:
        //.subscribe(CompletableHelper.toObserver(future)) - it reports the failure or success to the `done`
        // future.
        
        // To remove
        future.complete();
        //----

    });
}
 
Example #15
Source File: DiscoveryRecordInjector.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
public Single<Record> resolve(Class<? extends Single<Record>> rawType, Type genericType, Annotation[] annotations) {
	ServiceDiscovery discovery = AppGlobals.get().getGlobal(ServiceDiscovery.class);
	for (Annotation annotation : annotations) {
		if(annotation.annotationType() == ServiceName.class) {
			String serviceName = ((ServiceName) annotation).value();
			return discovery.rxGetRecord(record -> record.getName().equals(serviceName));
		}
	}
	return null;
}
 
Example #16
Source File: RXEventBusService.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
public static <T> Single<T> rxGetProxy(ServiceDiscovery discovery, Class<T> clientClass, Function<Record, Boolean>
    filter) {
    return new AsyncResultSingle<>(handler ->
        EventBusService.getServiceProxy(discovery, filter, clientClass, handler)
    );
}
 
Example #17
Source File: RXCompulsiveTraderVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> future) {
    String company = TraderUtils.pickACompany();
    int numberOfShares = TraderUtils.pickANumber();
    System.out.println("Java-RX compulsive trader configured for company " + company + " and shares: " +
        numberOfShares);


    ServiceDiscovery.create(vertx, discovery -> {
        Single<PortfolioService> retrieveThePortfolioService = RXEventBusService.rxGetProxy(discovery, PortfolioService.class,
            rec -> rec.getName().equalsIgnoreCase("portfolio"));

        Single<MessageConsumer<JsonObject>> retrieveTheMarket = MessageSource.rxGetConsumer(discovery,
            rec -> rec.getName().equalsIgnoreCase("market-data"));

        //TODO
        //----

        // TODO 1 - "wait" for both single to be completed (using Single.zip or Single.zipWith methods)
        retrieveThePortfolioService.zipWith(retrieveTheMarket, (ps, consumer) -> {

        // TODO 2 - When both single have completed, attach the handler to the message consumer to execute the
            // trading logic

            consumer.handler(message ->
                // TODO 3 - Use the TraderUtils.drumpTradingLogic method returning a Completable. Don't forget to
                // subscribe to it, or nothing will happen. Return "true" to comply with the "zip" operator
                // signature.
                
                TraderUtils.dumbTradingLogic(company, numberOfShares, ps, message.body()).subscribe());
            // We need to return something as requested by the "zip" signature.
            return true;
        })

            // TODO 4 - Transform the output into a Completable (toCompletable) and subscribe to it using:
            //.subscribe(CompletableHelper.toObserver(future)) - it reports the failure or success to the `done`
            // future.
            .toCompletable()
            .subscribe(CompletableHelper.toObserver(future));
        //----

    });
}
 
Example #18
Source File: RXEventBusService.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
public static <T> Single<T> rxGetProxy(ServiceDiscovery discovery, Class<T> clientClass, Function<Record, Boolean>
    filter) {
    return new AsyncResultSingle<>(handler ->
        EventBusService.getServiceProxy(discovery, filter, clientClass, handler)
    );
}
 
Example #19
Source File: PortfolioServiceImpl.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
public PortfolioServiceImpl(Vertx vertx, ServiceDiscovery discovery, double initialCash) {
    this.vertx = vertx;
    this.portfolio = new Portfolio().setCash(initialCash);
    this.discovery = discovery;
}
 
Example #20
Source File: PortfolioServiceImpl.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
public PortfolioServiceImpl(Vertx vertx, ServiceDiscovery discovery, double initialCash) {
    this.vertx = vertx;
    this.portfolio = new Portfolio().setCash(initialCash);
    this.discovery = discovery;
}