io.vertx.core.VertxOptions Java Examples

The following examples show how to use io.vertx.core.VertxOptions. 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: Service.java    From xyz-hub with Apache License 2.0 7 votes vote down vote up
/**
 * The service entry point.
 */
public static void main(String[] arguments) {
  Configurator.initialize("default", CONSOLE_LOG_CONFIG);
  final ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file").setConfig(new JsonObject().put("path", "config.json"));
  final ConfigStoreOptions envConfig = new ConfigStoreOptions().setType("env");
  final ConfigStoreOptions sysConfig = new ConfigStoreOptions().setType("sys");
  final ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore).addStore(envConfig).addStore(sysConfig);
  boolean debug = Arrays.asList(arguments).contains("--debug");

  final VertxOptions vertxOptions = new VertxOptions()
    .setWorkerPoolSize(NumberUtils.toInt(System.getenv(VERTX_WORKER_POOL_SIZE), 128))
    .setPreferNativeTransport(true);

  if (debug) {
    vertxOptions
        .setBlockedThreadCheckInterval(TimeUnit.MINUTES.toMillis(1))
        .setMaxEventLoopExecuteTime(TimeUnit.MINUTES.toMillis(1))
        .setMaxWorkerExecuteTime(TimeUnit.MINUTES.toMillis(1))
        .setWarningExceptionTime(TimeUnit.MINUTES.toMillis(1));
  }

  vertx = Vertx.vertx(vertxOptions);
  webClient = WebClient.create(Service.vertx, new WebClientOptions().setUserAgent(XYZ_HUB_USER_AGENT));
  ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
  retriever.getConfig(Service::onConfigLoaded);
}
 
Example #2
Source File: RxVertxTestBase.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
protected void startNodes(int numNodes, VertxOptions options) {
    CountDownLatch latch = new CountDownLatch(numNodes);
    vertices = new Vertx[numNodes];
    for (int i = 0; i < numNodes; i++) {
        int index = i;
        clusteredVertx(options.setClusterHost("localhost").setClusterPort(0).setClustered(true)
                .setClusterManager(getClusterManager()), ar -> {
            try {
                if (ar.failed()) {
                    ar.cause().printStackTrace();
                }
                assertTrue("Failed to start node", ar.succeeded());
                vertices[index] = ar.result();
            }
            finally {
                latch.countDown();
            }
        });
    }
    try {
        assertTrue(latch.await(2, TimeUnit.MINUTES));
    } catch (InterruptedException e) {
        fail(e.getMessage());
    }
}
 
Example #3
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
public void setupWithCompositeRegistry() {
  CompositeMeterRegistry myRegistry = new CompositeMeterRegistry();
  myRegistry.add(new JmxMeterRegistry(s -> null, Clock.SYSTEM));
  myRegistry.add(new GraphiteMeterRegistry(s -> null, Clock.SYSTEM));

  Vertx vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setMicrometerRegistry(myRegistry)
      .setEnabled(true)));
}
 
Example #4
Source File: TestMain.java    From Summer with MIT License 6 votes vote down vote up
public static void main(String args[]){

        VertxOptions options = new VertxOptions();
        options.setBlockedThreadCheckInterval(20000);
        options.setMaxEventLoopExecuteTime(20000);
        SummerServer summerServer =SummerServer.create("localhost",8080,options);

        DeploymentOptions deploymentOptions = new DeploymentOptions();
        summerServer.getVertx().
                deployVerticle(MyVerticle.class.getName());
        deploymentOptions.setWorker(true);
        summerServer.getSummerRouter().registerResource(Hello.class);
        summerServer.getVertx().
                deployVerticle(SummerServer.WebServer.class.getName());
        summerServer.start(deploymentOptions);
    }
 
Example #5
Source File: CustomEndpointTest.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp(TestContext testContext) {
    configuration = new InferenceConfiguration()
            .protocol(ServerProtocol.HTTP)
            .pipeline(SequencePipeline.builder()
                    .add(new LoggingStep().log(LoggingStep.Log.KEYS_AND_VALUES).logLevel(Level.ERROR))
                    .build())
            .customEndpoints(Collections.singletonList(CustomHttpEndpoint.class.getName()));

    Async async = testContext.async();

    vertx = DeployKonduitServing.deploy(new VertxOptions(),
            new DeploymentOptions(),
            configuration,
            handler -> {
                if(handler.succeeded()) {
                    inferenceDeploymentResult = handler.result();
                    async.complete();
                } else {
                    testContext.fail(handler.cause());
                }
            });
}
 
Example #6
Source File: Vertx3GatewayFileRegistryServer.java    From apiman with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
    try {
        gatewayStartLatch = new CountDownLatch(1);

        vertx = Vertx.vertx(new VertxOptions()
                .setBlockedThreadCheckInterval(99999));
        echoServer.start();

        DeploymentOptions options = new DeploymentOptions().
                setConfig(vertxConf);

        vertx.deployVerticle(InitVerticle.class.getCanonicalName(),
                options,
                result -> {
                    System.out.println("Deployed init verticle! " + (result.failed() ? "failed" : "succeeded"));
                    gatewayStartLatch.countDown();
                });

        gatewayStartLatch.await();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: Examples.java    From vertx-hazelcast with Apache License 2.0 6 votes vote down vote up
public void liteMemberConfig() {
  Config hazelcastConfig = ConfigUtil.loadConfig()
    .setLiteMember(true);

  ClusterManager mgr = new HazelcastClusterManager(hazelcastConfig);

  VertxOptions options = new VertxOptions().setClusterManager(mgr);

  Vertx.clusteredVertx(options, res -> {
    if (res.succeeded()) {
      Vertx vertx = res.result();
    } else {
      // failed!
    }
  });
}
 
Example #8
Source File: TestMetricsEndpoint.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp(TestContext testContext) {
    configuration = new InferenceConfiguration()
            .protocol(ServerProtocol.HTTP)
            .pipeline(SequencePipeline.builder()
                    .add(new LoggingStep().log(LoggingStep.Log.KEYS_AND_VALUES).logLevel(Level.ERROR))
                    .add(new MetricsTestingStep())
                    .build());

    Async async = testContext.async();

    vertx = DeployKonduitServing.deploy(new VertxOptions(),
            new DeploymentOptions(),
            configuration,
            handler -> {
                if(handler.succeeded()) {
                    inferenceDeploymentResult = handler.result();
                    async.complete();
                } else {
                    testContext.fail(handler.cause());
                }
            });
}
 
Example #9
Source File: DropwizardHelper.java    From okapi with Apache License 2.0 6 votes vote down vote up
/**
 * Configure Dropwizard helper.
 * @param graphiteHost graphite server host
 * @param port  graphits server port
 * @param tu time unit
 * @param period reporting period
 * @param vopt Vert.x options
 * @param hostName logical hostname for this node (reporting)
 */
public static void config(String graphiteHost, int port, TimeUnit tu,
        int period, VertxOptions vopt, String hostName) {
  final String registryName = "okapi";
  MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);

  DropwizardMetricsOptions metricsOpt = new DropwizardMetricsOptions();
  metricsOpt.setEnabled(true).setRegistryName(registryName);
  vopt.setMetricsOptions(metricsOpt);
  Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, port));
  final String prefix = "folio.okapi." + hostName;
  GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
          .prefixedWith(prefix)
          .build(graphite);
  reporter.start(period, tu);

  logger.info("Metrics remote {}:{} this {}", graphiteHost, port, prefix);
}
 
Example #10
Source File: VertxEmbeddedContainer.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart() {
    instances = (instances < 1) ? VertxOptions.DEFAULT_EVENT_LOOP_POOL_SIZE : instances;
    logger.info("Starting Vertx container and deploy Gateway Verticles [{} instance(s)]", instances);

    DeploymentOptions options = new DeploymentOptions().setInstances(instances);

    Single<String> deployment = vertx.rxDeployVerticle(SpringVerticleFactory.VERTICLE_PREFIX + ':' + GraviteeVerticle.class.getName(), options);

    deployment.subscribe(id -> {
        // Deployed
        deploymentId = id;
    }, err -> {
        // Could not deploy
        logger.error("Unable to start HTTP server", err.getCause());

        // HTTP Server is a required component. Shutdown if not available
        Runtime.getRuntime().exit(1);
    });
}
 
Example #11
Source File: PrometheusMetricsITest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldStartEmbeddedServer(TestContext context) {
  vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)
        .setStartEmbeddedServer(true)
        .setEmbeddedServerOptions(new HttpServerOptions().setPort(9090)))
      .addLabels(Label.LOCAL, Label.HTTP_PATH, Label.REMOTE)
      .setEnabled(true)));

  Async async = context.async();
  // First "blank" connection to trigger some metrics
  PrometheusTestHelper.tryConnect(vertx, context, 9090, "localhost", "/metrics", r1 -> {
    // Delay to make "sure" metrics are populated
    vertx.setTimer(500, l ->
      // Second connection, this time actually reading the metrics content
      PrometheusTestHelper.tryConnect(vertx, context, 9090, "localhost", "/metrics", body -> {
          context.verify(v2 -> assertThat(body.toString())
            .contains("vertx_http_client_requests{local=\"?\",method=\"GET\",path=\"/metrics\",remote=\"localhost:9090\"")
            .doesNotContain("vertx_http_client_responseTime_seconds_bucket"));
          async.complete();
      }));
  });
  async.awaitSuccess(10000);
}
 
Example #12
Source File: PrometheusMetricsITest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBindExistingServer(TestContext context) {
  vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true))
      .setEnabled(true)));

  Router router = Router.router(vertx);
  router.route("/custom").handler(routingContext -> {
    PrometheusMeterRegistry prometheusRegistry = (PrometheusMeterRegistry) BackendRegistries.getDefaultNow();
    String response = prometheusRegistry.scrape();
    routingContext.response().end(response);
  });
  vertx.createHttpServer().requestHandler(router).exceptionHandler(context.exceptionHandler()).listen(8081);

  Async async = context.async();
  PrometheusTestHelper.tryConnect(vertx, context, 8081, "localhost", "/custom", body -> {
    context.verify(v -> assertThat(body.toString())
          .contains("vertx_http_"));
    async.complete();
  });
  async.awaitSuccess(10000);
}
 
Example #13
Source File: PrometheusMetricsITest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldExcludeCategory(TestContext context) {
  vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)
        .setStartEmbeddedServer(true)
        .setEmbeddedServerOptions(new HttpServerOptions().setPort(9090)))
      .addDisabledMetricsCategory(MetricsDomain.HTTP_SERVER)
      .addLabels(Label.LOCAL, Label.REMOTE)
      .setEnabled(true)));

  Async async = context.async();
  PrometheusTestHelper.tryConnect(vertx, context, 9090, "localhost", "/metrics", body -> {
    context.verify(v -> assertThat(body.toString())
      .contains("vertx_http_client_connections{local=\"?\",remote=\"localhost:9090\",} 1.0")
      .doesNotContain("vertx_http_server_connections{local=\"0.0.0.0:9090\",remote=\"_\",} 1.0"));
    async.complete();
  });
  async.awaitSuccess(10000);
}
 
Example #14
Source File: VxApiLauncher.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 设置vert.x配置
 */
@Override
public void beforeStartingVertx(VertxOptions options) {
	try {
		byte[] bytes = Files.readAllBytes(PathUtil.getPath("conf.json"));
		Buffer buff = Buffer.buffer(bytes);
		// 总配置文件
		JsonObject conf = buff.toJsonObject();
		// vert.x配置文件
		JsonObject vertxc = conf.getJsonObject("vertx", getDefaultVertxConfig());
		initVertxConfig(vertxc, options);
		// 集群配置文件
		JsonObject clusterc = conf.getJsonObject("cluster", new JsonObject().put("clusterType", CLUSTER_TYPE));
		if (!CLUSTER_TYPE.equals(clusterc.getString("clusterType"))) {
			ClusterManager cmgr = VxApiClusterManagerFactory.getClusterManager(clusterc.getString("clusterType"),
					clusterc.getJsonObject("clusterConf", getDefaultClusterConfig()));
			options.setClusterManager(cmgr);
			options.setClustered(true);
		}
	} catch (IOException e) {
		throw new FileSystemException(e);
	}
}
 
Example #15
Source File: UnixDomainSocketTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void connectWithVertxInstance(TestContext context) {
  assumeTrue(options.isUsingDomainSocket());
  Vertx vertx = Vertx.vertx(new VertxOptions().setPreferNativeTransport(true));
  try {
    client = PgPool.pool(vertx, new PgConnectOptions(options), new PoolOptions());
    Async async = context.async();
    client.getConnection(context.asyncAssertSuccess(pgConnection -> {
      async.complete();
      pgConnection.close();
    }));
    async.await();
  } finally {
    vertx.close();
  }
}
 
Example #16
Source File: CustomMicrometerMetricsITest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPublishQuantilesWithProvidedRegistry(TestContext context) throws Exception {
  PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
  vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)
        .setPublishQuantiles(true)
        .setStartEmbeddedServer(true)
        .setEmbeddedServerOptions(new HttpServerOptions().setPort(9090)))
      .setMicrometerRegistry(registry)
      .setEnabled(true)));

  Async async = context.async();
  // Dummy connection to trigger some metrics
  PrometheusTestHelper.tryConnect(vertx, context, 9090, "localhost", "/metrics", r1 -> {
    // Delay to make "sure" metrics are populated
    vertx.setTimer(500, l -> {
      assertThat(registry.scrape()).contains("vertx_http_client_responseTime_seconds_bucket{code=\"200\"");
      async.complete();
    });
  });
  async.awaitSuccess(10000);
}
 
Example #17
Source File: VertxNetUtils.java    From Lealone-Plugins with Apache License 2.0 6 votes vote down vote up
public static Vertx getVertx(Map<String, String> config) {
    if (vertx == null) {
        synchronized (VertxNetUtils.class) {
            if (vertx == null) {
                Integer blockedThreadCheckInterval = Integer.MAX_VALUE;
                if (config.containsKey("blocked_thread_check_interval")) {
                    blockedThreadCheckInterval = Integer.parseInt(config.get("blocked_thread_check_interval"));
                    if (blockedThreadCheckInterval <= 0)
                        blockedThreadCheckInterval = Integer.MAX_VALUE;
                }
                VertxOptions opt = new VertxOptions();
                opt.setBlockedThreadCheckInterval(blockedThreadCheckInterval);
                vertx = Vertx.vertx(opt);
            }
        }
    }
    return vertx;
}
 
Example #18
Source File: VertxNetClientServerMetricsTest.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext ctx) {
  vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions()
      .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true))
    .addDisabledMetricsCategory(MetricsDomain.EVENT_BUS)
    .addLabels(Label.LOCAL, Label.REMOTE)
    .setRegistryName(registryName)
    .setEnabled(true)))
    .exceptionHandler(ctx.exceptionHandler());

  // Filter out remote labels
  BackendRegistries.getNow(registryName).config().meterFilter(
    MeterFilter.replaceTagValues(Label.REMOTE.toString(), s -> "_", "localhost:9194"));

  // Setup server
  Async serverReady = ctx.async();
  vertx.deployVerticle(new AbstractVerticle() {
    @Override
    public void start(Promise<Void> future) throws Exception {
      netServer = vertx.createNetServer();
      netServer
        .connectHandler(socket -> socket.handler(buffer -> socket.write(SERVER_RESPONSE)))
        .listen(9194, "localhost", r -> {
          if (r.failed()) {
            ctx.fail(r.cause());
          } else {
            serverReady.complete();
          }
        });
    }
  });
  serverReady.awaitSuccess();
}
 
Example #19
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
public void setupAndAccessCustomRegistry() {
  Vertx vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(
    new MicrometerMetricsOptions()
      .setInfluxDbOptions(new VertxInfluxDbOptions().setEnabled(true)) // or VertxPrometheusOptions
      .setRegistryName("my registry")
      .setEnabled(true)));

  // Later on:
  MeterRegistry registry = BackendRegistries.getNow("my registry");
}
 
Example #20
Source File: VxmsGateway.java    From kube_vertx_demo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    DeploymentOptions options = new DeploymentOptions().setInstances(1).
            setConfig(new JsonObject().put("local", true).put("host", "0.0.0.0").put("port", 8181));
    VertxOptions vOpts = new VertxOptions();
    vOpts.setClustered(true);
    Vertx.clusteredVertx(vOpts, cluster -> {
        if (cluster.succeeded()) {
            final Vertx result = cluster.result();
            result.deployVerticle(VxmsGateway.class.getName(), options, handle -> {

            });
        }
    });

}
 
Example #21
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
public void setupWithLabelsEnabled() {
  Vertx vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(
    new MicrometerMetricsOptions()
      .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true))
      .setLabels(EnumSet.of(Label.REMOTE, Label.LOCAL, Label.HTTP_CODE, Label.HTTP_PATH))
      .setEnabled(true)));
}
 
Example #22
Source File: IgniteDiscoveryImplClusteredTest.java    From vertx-ignite with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  VertxOptions options = new VertxOptions()
    .setClusterManager(new IgniteClusterManager());
  Vertx.clusteredVertx(options, ar -> {
    vertx = ar.result();
  });
  await().until(() -> vertx != null);
  discovery = new DiscoveryImpl(vertx, new ServiceDiscoveryOptions());
}
 
Example #23
Source File: InfluxDbReporterITest.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSendDataToInfluxDb(TestContext context) throws Exception {
  // Mock an influxdb server
  Async asyncInflux = context.async();
  InfluxDbTestHelper.simulateInfluxServer(vertxForSimulatedServer, context, 8086, body -> {
    if (body.contains("vertx_eventbus_handlers,address=test-eb,metric_type=gauge value=1")) {
      asyncInflux.complete();
    }
  });

  vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setInfluxDbOptions(new VertxInfluxDbOptions()
        .setStep(1)
        .setDb("mydb")
        .setEnabled(true))
      .setRegistryName(REGITRY_NAME)
      .addLabels(Label.EB_ADDRESS)
      .setEnabled(true)));

  // Send something on the eventbus and wait til it's received
  Async asyncEB = context.async();
  vertx.eventBus().consumer("test-eb", msg -> asyncEB.complete());
  vertx.eventBus().publish("test-eb", "test message");
  asyncEB.await(2000);

  // Await influx
  asyncInflux.awaitSuccess(2000);
}
 
Example #24
Source File: VertxCoreRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void setEventBusOptions(VertxConfiguration conf, VertxOptions options) {
    EventBusConfiguration eb = conf.eventbus;
    EventBusOptions opts = new EventBusOptions();
    opts.setAcceptBacklog(eb.acceptBacklog.orElse(-1));
    opts.setClientAuth(ClientAuth.valueOf(eb.clientAuth.toUpperCase()));
    opts.setConnectTimeout((int) (Math.min(Integer.MAX_VALUE, eb.connectTimeout.toMillis())));
    // todo: use timeUnit cleverly
    opts.setIdleTimeout(
            eb.idleTimeout.isPresent() ? (int) Math.max(1, Math.min(Integer.MAX_VALUE, eb.idleTimeout.get().getSeconds()))
                    : 0);
    opts.setSendBufferSize(eb.sendBufferSize.orElse(-1));
    opts.setSoLinger(eb.soLinger.orElse(-1));
    opts.setSsl(eb.ssl);
    opts.setReceiveBufferSize(eb.receiveBufferSize.orElse(-1));
    opts.setReconnectAttempts(eb.reconnectAttempts);
    opts.setReconnectInterval(eb.reconnectInterval.toMillis());
    opts.setReuseAddress(eb.reuseAddress);
    opts.setReusePort(eb.reusePort);
    opts.setTrafficClass(eb.trafficClass.orElse(-1));
    opts.setTcpKeepAlive(eb.tcpKeepAlive);
    opts.setTcpNoDelay(eb.tcpNoDelay);
    opts.setTrustAll(eb.trustAll);

    // Certificates and trust.
    configurePemKeyCertOptions(opts, eb.keyCertificatePem);
    configureJksKeyCertOptions(opts, eb.keyCertificateJks);
    configurePfxKeyCertOptions(opts, eb.keyCertificatePfx);

    configurePemTrustOptions(opts, eb.trustCertificatePem);
    configureJksKeyCertOptions(opts, eb.trustCertificateJks);
    configurePfxTrustOptions(opts, eb.trustCertificatePfx);

    options.setEventBusOptions(opts);
}
 
Example #25
Source File: MetricsTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext context) {
  String graphiteHost = System.getProperty("graphiteHost");

  final String registryName = "okapi";
  MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);

  // Note the setEnabled (true or false)
  DropwizardMetricsOptions metricsOpt = new DropwizardMetricsOptions().
          setEnabled(false).setRegistryName(registryName);

  vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(metricsOpt));

  reporter1 = ConsoleReporter.forRegistry(registry).build();
  reporter1.start(1, TimeUnit.SECONDS);

  if (graphiteHost != null) {
    Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, 2003));
    reporter2 = GraphiteReporter.forRegistry(registry)
            .prefixedWith("okapiserver")
            .build(graphite);
    reporter2.start(1, TimeUnit.MILLISECONDS);
  }

  DeploymentOptions opt = new DeploymentOptions()
    .setConfig(new JsonObject().put("port", Integer.toString(port)));


  vertx.deployVerticle(MainVerticle.class.getName(),
          opt, context.asyncAssertSuccess());
  httpClient = vertx.createHttpClient();
}
 
Example #26
Source File: VertxCoreProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
@Record(value = ExecutionTime.RUNTIME_INIT)
CoreVertxBuildItem build(VertxCoreRecorder recorder,
        LaunchModeBuildItem launchMode, ShutdownContextBuildItem shutdown, VertxConfiguration config,
        List<VertxOptionsConsumerBuildItem> vertxOptionsConsumers,
        BuildProducer<SyntheticBeanBuildItem> syntheticBeans,
        BuildProducer<EventLoopSupplierBuildItem> eventLoops,
        BuildProducer<ServiceStartBuildItem> serviceStartBuildItem) {

    Collections.sort(vertxOptionsConsumers);
    List<Consumer<VertxOptions>> consumers = new ArrayList<>(vertxOptionsConsumers.size());
    for (VertxOptionsConsumerBuildItem x : vertxOptionsConsumers) {
        consumers.add(x.getConsumer());
    }

    Supplier<Vertx> vertx = recorder.configureVertx(config,
            launchMode.getLaunchMode(), shutdown, consumers);
    syntheticBeans.produce(SyntheticBeanBuildItem.configure(Vertx.class)
            .types(Vertx.class)
            .scope(Singleton.class)
            .unremovable()
            .setRuntimeInit()
            .supplier(vertx).done());

    // Event loops are only usable after the core vertx instance is configured
    eventLoops.produce(new EventLoopSupplierBuildItem(recorder.mainSupplier(), recorder.bossSupplier()));

    return new CoreVertxBuildItem(vertx);
}
 
Example #27
Source File: PgPool.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
/**
 * Create a connection pool to the database configured with the given {@code connectOptions} and {@code poolOptions}.
 *
 * @param poolOptions the options for creating the pool
 * @return the connection pool
 */
static PgPool pool(PgConnectOptions connectOptions, PoolOptions poolOptions) {
  if (Vertx.currentContext() != null) {
    throw new IllegalStateException("Running in a Vertx context => use PgPool#pool(Vertx, PgConnectOptions, PoolOptions) instead");
  }
  VertxOptions vertxOptions = new VertxOptions();
  if (connectOptions.isUsingDomainSocket()) {
    vertxOptions.setPreferNativeTransport(true);
  }
  VertxInternal vertx = (VertxInternal) Vertx.vertx(vertxOptions);
  return PgPoolImpl.create(vertx.getOrCreateContext(), true, connectOptions, poolOptions);
}
 
Example #28
Source File: MicrometerMetricsExamples.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
public void setupJMXWithStepAndDomain() {
  Vertx vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(
    new MicrometerMetricsOptions()
      .setJmxMetricsOptions(new VertxJmxMetricsOptions().setEnabled(true)
        .setStep(5)
        .setDomain("my.metrics.domain"))
      .setEnabled(true)));
}
 
Example #29
Source File: Examples.java    From vertx-ignite with Apache License 2.0 5 votes vote down vote up
public void example3(Ignite ignite) {
  // Configuration code (omitted)

  ClusterManager clusterManager = new IgniteClusterManager(ignite);

  VertxOptions options = new VertxOptions().setClusterManager(clusterManager);
  Vertx.clusteredVertx(options, res -> {
    if (res.succeeded()) {
      Vertx vertx = res.result();
    } else {
      // failed!
    }
  });
}
 
Example #30
Source File: DockerModuleHandleTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testDockerVersionAtLocal(TestContext context) {
  VertxOptions options = new VertxOptions();
  options.setPreferNativeTransport(true);
  Vertx vertx = Vertx.vertx(options);
  LaunchDescriptor ld = new LaunchDescriptor();
  Ports ports = new Ports(9232, 9233);

  DockerModuleHandle dh = new DockerModuleHandle(vertx, ld,
    "mod-users-5.0.0-SNAPSHOT", ports, "localhost", 9232, new JsonObject());

  JsonObject versionRes = new JsonObject();
  Async async = context.async();
  dh.getUrl("/version", res -> {
    if (res.succeeded()) {
      versionRes.put("result", res.result());
    }
    async.complete();
  });
  async.await(1000);
  Assume.assumeTrue(versionRes.containsKey("result"));
  context.assertTrue(versionRes.getJsonObject("result").containsKey("Version"));

  // provoke 404 not found
  dh.deleteUrl("/version", "msg", context.asyncAssertFailure(cause -> {
    context.assertTrue(cause.getMessage().startsWith("msg HTTP error 404"),
      cause.getMessage());
    // provoke 404 not found
    dh.postUrlJson("/version", "msg", "{}", context.asyncAssertFailure(cause2 -> {
      context.assertTrue(cause2.getMessage().startsWith("msg HTTP error 404"),
        cause2.getMessage());
    }));
  }));
}