Java Code Examples for io.vertx.core.WorkerExecutor#executeBlocking()
The following examples show how to use
io.vertx.core.WorkerExecutor#executeBlocking() .
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: AsyncCompletion.java From incubator-tuweni with Apache License 2.0 | 6 votes |
/** * Returns a completion that completes after the given blocking action executes asynchronously on a vertx executor. * * @param executor A vertx executor. * @param action The blocking action to execute. * @return A completion. */ static AsyncCompletion executeBlocking(WorkerExecutor executor, Runnable action) { requireNonNull(action); CompletableAsyncCompletion completion = AsyncCompletion.incomplete(); executor.executeBlocking(future -> { action.run(); future.complete(); }, false, res -> { if (res.succeeded()) { completion.complete(); } else { completion.completeExceptionally(res.cause()); } }); return completion; }
Example 2
Source File: AsyncCompletion.java From cava with Apache License 2.0 | 6 votes |
/** * Returns a completion that completes after the given blocking action executes asynchronously on a vertx executor. * * @param executor A vertx executor. * @param action The blocking action to execute. * @return A completion. */ static AsyncCompletion executeBlocking(WorkerExecutor executor, Runnable action) { requireNonNull(action); CompletableAsyncCompletion completion = AsyncCompletion.incomplete(); executor.executeBlocking(future -> { action.run(); future.complete(); }, false, res -> { if (res.succeeded()) { completion.complete(); } else { completion.completeExceptionally(res.cause()); } }); return completion; }
Example 3
Source File: AsyncResult.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * Returns a result that, after the given blocking function executes asynchronously on a vertx executor and returns a * result, completes when the returned result completes, with the same value or exception. * * @param executor A vertx executor. * @param fn The function returning a result. * @param <T> The type of the returned result's value. * @return A new result. */ static <T> AsyncResult<T> executeBlocking(WorkerExecutor executor, Supplier<T> fn) { requireNonNull(fn); CompletableAsyncResult<T> asyncResult = AsyncResult.incomplete(); executor.<T>executeBlocking(future -> future.complete(fn.get()), false, res -> { if (res.succeeded()) { asyncResult.complete(res.result()); } else { asyncResult.completeExceptionally(res.cause()); } }); return asyncResult; }
Example 4
Source File: AsyncResult.java From cava with Apache License 2.0 | 5 votes |
/** * Returns a result that, after the given blocking function executes asynchronously on a vertx executor and returns a * result, completes when the returned result completes, with the same value or exception. * * @param executor A vertx executor. * @param fn The function returning a result. * @param <T> The type of the returned result's value. * @return A new result. */ static <T> AsyncResult<T> executeBlocking(WorkerExecutor executor, Supplier<T> fn) { requireNonNull(fn); CompletableAsyncResult<T> asyncResult = AsyncResult.incomplete(); executor.<T>executeBlocking(future -> future.complete(fn.get()), false, res -> { if (res.succeeded()) { asyncResult.complete(res.result()); } else { asyncResult.completeExceptionally(res.cause()); } }); return asyncResult; }
Example 5
Source File: VertxPoolMetricsTest.java From vertx-micrometer-metrics with Apache License 2.0 | 4 votes |
@Test public void shouldReportNamedPoolMetrics(TestContext context) throws InterruptedException { int maxPoolSize = 8; int taskCount = maxPoolSize * 3; int sleepMillis = 30; vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions() .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)) .addLabels(Label.POOL_NAME) .setEnabled(true))) .exceptionHandler(context.exceptionHandler()); // Setup executor WorkerExecutor workerExecutor = vertx.createSharedWorkerExecutor("test-worker", maxPoolSize); Async ready = context.async(taskCount); for (int i = 0; i < taskCount; i++) { workerExecutor.executeBlocking(future -> { try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { throw new RuntimeException(e); } future.complete(); }, false, context.asyncAssertSuccess(v -> { ready.countDown(); })); } ready.awaitSuccess(); RegistryInspector.waitForValue( vertx, context, "vertx.pool.completed[pool_name=test-worker,pool_type=worker]$COUNT", value -> value.intValue() == taskCount); List<RegistryInspector.Datapoint> datapoints = listDatapoints(startsWith("vertx.pool")); assertThat(datapoints).hasSize(10).contains( dp("vertx.pool.queue.size[pool_name=test-worker,pool_type=worker]$VALUE", 0), dp("vertx.pool.inUse[pool_name=test-worker,pool_type=worker]$VALUE", 0), dp("vertx.pool.ratio[pool_name=test-worker,pool_type=worker]$VALUE", 0), dp("vertx.pool.completed[pool_name=test-worker,pool_type=worker]$COUNT", taskCount), dp("vertx.pool.queue.delay[pool_name=test-worker,pool_type=worker]$COUNT", taskCount), dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$COUNT", taskCount)); assertThat(datapoints) .usingFieldByFieldElementComparator() .usingComparatorForElementFieldsWithType(new DoubleComparator(0.1), Double.class) .contains(dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$MAX", sleepMillis / 1000d)); class GreaterOrEqualsComparator implements Comparator<Double> { @Override public int compare(Double o1, Double o2) { return o1 < o2 ? -1 : 0; } } assertThat(datapoints) .usingFieldByFieldElementComparator() .usingComparatorForElementFieldsWithType(new GreaterOrEqualsComparator(), Double.class) .contains( dp("vertx.pool.usage[pool_name=test-worker,pool_type=worker]$TOTAL_TIME", taskCount * sleepMillis / 1000d)); }
Example 6
Source File: ProcessorTopicSchemaRegistry.java From df_data_service with Apache License 2.0 | 4 votes |
/** * Retrieve all subjects first; and then retrieve corresponding subject's schema information. * Here, we'll filter topic-value and topic-key subject since these are used by the kafka and CR. * These subject are not available until SourceRecord is available. * Use block rest client, but unblock using vertx worker. * * @param routingContext * @param schema_registry_host_and_port */ public static void forwardGetAllSchemas(Vertx vertx, RoutingContext routingContext, String schema_registry_host_and_port) { StringBuffer returnString = new StringBuffer(); WorkerExecutor executor = vertx.createSharedWorkerExecutor("forwardGetAllSchemas_pool_" + new ObjectId(), ConstantApp.WORKER_POOL_SIZE, ConstantApp.MAX_RUNTIME); executor.executeBlocking(future -> { String restURI = "http://" + schema_registry_host_and_port + "/subjects"; int status_code = ConstantApp.STATUS_CODE_OK; try { HttpResponse<String> res = Unirest .get(restURI) .header("accept", ConstantApp.AVRO_REGISTRY_CONTENT_TYPE) .asString(); if (res == null) { status_code = ConstantApp.STATUS_CODE_BAD_REQUEST; } else if (res.getStatus() != ConstantApp.STATUS_CODE_OK) { status_code = res.getStatus(); } else { String subjects = res.getBody(); // ["Kafka-value","Kafka-key"] LOG.debug("All subjects received are " + subjects); StringBuffer strBuff = new StringBuffer(); int count = 0; if (subjects.compareToIgnoreCase("[]") != 0) { // Has active subjects for (String subject : subjects.substring(2, subjects.length() - 2).split("\",\"")) { // If the subject is internal one, such as topic-key or topic-value if(subject.contains("df_meta") || subject.contains("-value") || subject.contains("-key")) continue; HttpResponse<JsonNode> resSubject = Unirest .get(restURI + "/" + subject + "/versions/latest") .header("accept", ConstantApp.HTTP_HEADER_APPLICATION_JSON_CHARSET) .asJson(); if (resSubject == null) { status_code = ConstantApp.STATUS_CODE_BAD_REQUEST; } else if (resSubject.getStatus() != ConstantApp.STATUS_CODE_OK) { status_code = resSubject.getStatus(); } else { JSONObject jsonSchema = resSubject.getBody().getObject(); String compatibility = getCompatibilityOfSubject(schema_registry_host_and_port, subject); if (compatibility == null || compatibility.isEmpty()) compatibility = "NONE"; jsonSchema.put(ConstantApp.SCHEMA_REGISTRY_KEY_COMPATIBILITY, compatibility); // Repack subject to id, id to schema id jsonSchema.put("schemaId", jsonSchema.get("id")); jsonSchema.put("id", subject); String schema = jsonSchema.toString(); if (count == 0) strBuff.append("["); count ++; strBuff.append(schema).append(","); } } if (count > 0) returnString.append(strBuff.toString().substring(0, strBuff.toString().length() - 1) + "]"); //LOG.debug("returnString: " + returnString.toString()); } } } catch (JSONException | UnirestException e) { LOG.error(DFAPIMessage.logResponseMessage(9027, " exception -" + e.getCause())); status_code = ConstantApp.STATUS_CODE_BAD_REQUEST; } future.complete(status_code); }, res -> { Object result = HelpFunc.coalesce(res.result(), ConstantApp.STATUS_CODE_BAD_REQUEST); try { if (returnString == null || returnString.toString().isEmpty()) { HelpFunc.responseCorsHandleAddOn(routingContext.response()) .setStatusCode(Integer.parseInt(result.toString())) .putHeader("X-Total-Count", "0") .end("[]"); } else { HelpFunc.responseCorsHandleAddOn(routingContext.response()) .setStatusCode(Integer.parseInt(result.toString())) .putHeader("X-Total-Count", new JSONArray(returnString.toString()).length() + "") .end(HelpFunc.stringToJsonFormat( HelpFunc.sortJsonArray(routingContext, new JSONArray(returnString.toString()) ).toString()) ); } } catch (JSONException je) { LOG.error(DFAPIMessage.logResponseMessage(9027, " exception - " + je.getCause())); } executor.close(); }); }
Example 7
Source File: VertxUtil.java From database with Apache License 2.0 | 4 votes |
/** * Equivalent to {@link Vertx#executeBlocking(Handler, boolean, Handler)}, * but preserves the {@link MDC} correctly. */ public static <T> void executeBlocking(WorkerExecutor executor, Handler<Future<T>> future, boolean ordered, Handler<AsyncResult<T>> handler) { executor.executeBlocking(mdc(future), ordered, mdcEventLoop(handler)); }