Java Code Examples for io.vertx.sqlclient.PoolOptions

The following examples show how to use io.vertx.sqlclient.PoolOptions. These examples are extracted from open source projects. 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
protected Pool configurePool(Map configurationValues, Vertx vertx) {
	URI uri = jdbcUrl(configurationValues);
	SqlConnectOptions connectOptions = sqlConnectOptions( uri );
	PoolOptions poolOptions = poolOptions( configurationValues );

	try {
		// First try to load the Pool using the standard ServiceLoader pattern
		// This only works if exactly 1 Driver is on the classpath.
		return Pool.pool( vertx, connectOptions, poolOptions );
	}
	catch (ServiceConfigurationError e) {
		// Backup option if multiple drivers are on the classpath.
		// We will be able to remove this once Vertx 3.9.2 is available
		return findDriver( uri, e ).createPool( vertx, connectOptions, poolOptions );
	}
}
 
Example 2
Source Project: vertx-in-action   Source File: EventsVerticle.java    License: MIT License 6 votes vote down vote up
@Override
public Completable rxStart() {
  eventConsumer = KafkaConsumer.create(vertx, KafkaConfig.consumer("activity-service"));
  updateProducer = KafkaProducer.create(vertx, KafkaConfig.producer());
  pgPool = PgPool.pool(vertx, PgConfig.pgConnectOpts(), new PoolOptions());

  eventConsumer
    .subscribe("incoming.steps")
    .toFlowable()
    .flatMap(this::insertRecord)
    .flatMap(this::generateActivityUpdate)
    .flatMap(this::commitKafkaConsumerOffset)
    .doOnError(err -> logger.error("Woops", err))
    .retryWhen(this::retryLater)
    .subscribe();

  return Completable.complete();
}
 
Example 3
Source Project: vertx-in-action   Source File: EventProcessingTest.java    License: MIT License 6 votes vote down vote up
@BeforeEach
void resetPgAndKafka(Vertx vertx, VertxTestContext testContext) {
  consumer = KafkaConsumer.create(vertx, KafkaConfig.consumer("activity-service-test-" + System.currentTimeMillis()));
  producer = KafkaProducer.create(vertx, KafkaConfig.producer());
  KafkaAdminClient adminClient = KafkaAdminClient.create(vertx, KafkaConfig.producer());

  PgPool pgPool = PgPool.pool(vertx, PgConfig.pgConnectOpts(), new PoolOptions());
  pgPool.query("DELETE FROM stepevent")
    .rxExecute()
    .flatMapCompletable(rs -> adminClient.rxDeleteTopics(Arrays.asList("incoming.steps", "daily.step.updates")))
    .andThen(Completable.fromAction(pgPool::close))
    .onErrorComplete()
    .subscribe(
      testContext::completeNow,
      testContext::failNow);
}
 
Example 4
Source Project: vertx-in-action   Source File: ApiTest.java    License: MIT License 6 votes vote down vote up
@BeforeEach
void prepareDb(Vertx vertx, VertxTestContext testContext) {
  String insertQuery = "INSERT INTO stepevent VALUES($1, $2, $3::timestamp, $4)";
  LocalDateTime now = LocalDateTime.now();
  List<Tuple> data = Arrays.asList(
    Tuple.of("123", 1, LocalDateTime.of(2019, 4, 1, 23, 0), 6541),
    Tuple.of("123", 2, LocalDateTime.of(2019, 5, 20, 10, 0), 200),
    Tuple.of("123", 3, LocalDateTime.of(2019, 5, 21, 10, 10), 100),
    Tuple.of("456", 1, LocalDateTime.of(2019, 5, 21, 10, 15), 123),
    Tuple.of("123", 4, LocalDateTime.of(2019, 5, 21, 11, 0), 320),
    Tuple.of("abc", 1, now.minus(1, ChronoUnit.HOURS), 1000),
    Tuple.of("def", 1, now.minus(2, ChronoUnit.HOURS), 100),
    Tuple.of("def", 2, now.minus(30, ChronoUnit.MINUTES), 900),
    Tuple.of("abc", 2, now, 1500)
  );
  PgPool pgPool = PgPool.pool(vertx, PgConfig.pgConnectOpts(), new PoolOptions());

  pgPool.query("DELETE FROM stepevent")
    .rxExecute()
    .flatMap(rows -> pgPool.preparedQuery(insertQuery).rxExecuteBatch(data))
    .ignoreElement()
    .andThen(vertx.rxDeployVerticle(new ActivityApiVerticle()))
    .ignoreElement()
    .andThen(Completable.fromAction(pgPool::close))
    .subscribe(testContext::completeNow, testContext::failNow);
}
 
Example 5
Source Project: vertx-sql-client   Source File: PgClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void configureFromDataObject(Vertx vertx) {

    // Data object
    PgConnectOptions connectOptions = new PgConnectOptions()
      .setPort(5432)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool Options
    PoolOptions poolOptions = new PoolOptions().setMaxSize(5);

    // Create the pool from the data object
    PgPool pool = PgPool.pool(vertx, connectOptions, poolOptions);

    pool.getConnection(ar -> {
      // Handling your connection
    });
  }
 
Example 6
Source Project: vertx-sql-client   Source File: PgClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void connecting01() {

    // Connect options
    PgConnectOptions connectOptions = new PgConnectOptions()
      .setPort(5432)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);

    // Create the pooled client
    PgPool client = PgPool.pool(connectOptions, poolOptions);
  }
 
Example 7
Source Project: vertx-sql-client   Source File: MySQLClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void connecting01() {

    // Connect options
    MySQLConnectOptions connectOptions = new MySQLConnectOptions()
      .setPort(3306)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);

    // Create the pooled client
    MySQLPool client = MySQLPool.pool(connectOptions, poolOptions);
  }
 
Example 8
Source Project: vertx-sql-client   Source File: PgPoolTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectionFailure(TestContext ctx) {
  Async async = ctx.async();
  ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost());
  AtomicReference<ProxyServer.Connection> proxyConn = new AtomicReference<>();
  proxy.proxyHandler(conn -> {
    proxyConn.set(conn);
    conn.connect();
  });
  PgPool pool = createPool(new PgConnectOptions(options).setPort(8080).setHost("localhost"),
    new PoolOptions()
      .setMaxSize(1)
      .setMaxWaitQueueSize(0)
  );
  pool.getConnection(ctx.asyncAssertFailure(err -> {
    proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> {
      pool.getConnection(ctx.asyncAssertSuccess(conn -> {
        async.complete();
      }));
    }));
  }));
}
 
Example 9
Source Project: vertx-sql-client   Source File: UnixDomainSocketTest.java    License: 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 10
Source Project: vertx-sql-client   Source File: DB2ClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void connecting01() {

    // Connect options
    DB2ConnectOptions connectOptions = new DB2ConnectOptions()
      .setPort(50000)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);

    // Create the pooled client
    DB2Pool client = DB2Pool.pool(connectOptions, poolOptions);
  }
 
Example 11
Source Project: vertx-sql-client   Source File: DB2ClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void connecting02(Vertx vertx) {

    // Connect options
    DB2ConnectOptions connectOptions = new DB2ConnectOptions()
      .setPort(50000)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);
    // Create the pooled client
    DB2Pool client = DB2Pool.pool(vertx, connectOptions, poolOptions);
  }
 
Example 12
Source Project: vertx-sql-client   Source File: MySQLClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void connecting02(Vertx vertx) {

    // Connect options
    MySQLConnectOptions connectOptions = new MySQLConnectOptions()
      .setPort(3306)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);
    // Create the pooled client
    MySQLPool client = MySQLPool.pool(vertx, connectOptions, poolOptions);
  }
 
Example 13
@Bean
public SimpleReactivePostgresTemplate reactivePostgresTemplate(Vertx vertx) {
    PgConnectOptions connectOptions = new PgConnectOptions()
        .setUser("sa")
        .setPassword("sa")
        .setDatabase("sa");
    PoolOptions poolOptions = new PoolOptions();
    PgPool pgPool = PgPool.pool(new io.vertx.axle.core.Vertx(vertx), connectOptions, poolOptions);

    BasicRelationalConverter converter = new BasicRelationalConverter(new RelationalMappingContext());
    ColumnEntityWriter entityWriter = new ColumnEntityWriter(converter);

    return new SimpleReactivePostgresTemplate(pgPool, entityWriter, converter);
}
 
Example 14
Source Project: vertx-in-action   Source File: ActivityApiVerticle.java    License: MIT License 5 votes vote down vote up
@Override
public Completable rxStart() {
  pgPool = PgPool.pool(vertx, PgConfig.pgConnectOpts(), new PoolOptions());

  Router router = Router.router(vertx);
  router.get("/:deviceId/total").handler(this::totalSteps);
  router.get("/:deviceId/:year/:month").handler(this::stepsOnMonth);
  router.get("/:deviceId/:year/:month/:day").handler(this::stepsOnDay);
  router.get("/ranking-last-24-hours").handler(this::ranking);

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example 15
Source Project: vertx-in-action   Source File: IntegrationTest.java    License: MIT License 5 votes vote down vote up
@BeforeAll
void prepareSpec(Vertx vertx, VertxTestContext testContext) {
  requestSpecification = new RequestSpecBuilder()
    .addFilters(asList(new ResponseLoggingFilter(), new RequestLoggingFilter()))
    .setBaseUri("http://localhost:4000/")
    .setBasePath("/api/v1")
    .build();

  String insertQuery = "INSERT INTO stepevent VALUES($1, $2, $3::timestamp, $4)";
  List<Tuple> data = Arrays.asList(
    Tuple.of("a1b2c3", 1, LocalDateTime.of(2019, 6, 16, 10, 3), 250),
    Tuple.of("a1b2c3", 2, LocalDateTime.of(2019, 6, 16, 12, 30), 1000),
    Tuple.of("a1b2c3", 3, LocalDateTime.of(2019, 6, 15, 23, 00), 5005)
  );
  PgPool pgPool = PgPool.pool(vertx, new PgConnectOptions()
    .setHost("localhost")
    .setDatabase("postgres")
    .setUser("postgres")
    .setPassword("vertx-in-action"), new PoolOptions());

  pgPool.preparedQuery(insertQuery)
    .rxExecuteBatch(data)
    .ignoreElement()
    .andThen(vertx.rxDeployVerticle(new PublicApiVerticle()))
    .ignoreElement()
    .andThen(vertx.rxDeployVerticle("tenksteps.userprofiles.UserProfileApiVerticle"))
    .ignoreElement()
    .andThen(vertx.rxDeployVerticle("tenksteps.activities.ActivityApiVerticle"))
    .ignoreElement()
    .andThen(Completable.fromAction(pgPool::close))
    .subscribe(testContext::completeNow, testContext::failNow);
}
 
Example 16
Source Project: vertx-sql-client   Source File: DriverTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatePoolFromDriver04(TestContext ctx) {
  Pool p = getDriver().createPool(Vertx.vertx(), defaultOptions(), new PoolOptions().setMaxSize(1));
  p.getConnection(ctx.asyncAssertSuccess(ar -> {
    ar.close();
  }));
}
 
Example 17
Source Project: quarkus   Source File: MySQLPoolRecorder.java    License: Apache License 2.0 5 votes vote down vote up
private MySQLPool initialize(Vertx vertx, DataSourceRuntimeConfig dataSourceRuntimeConfig,
        DataSourceReactiveRuntimeConfig dataSourceReactiveRuntimeConfig,
        DataSourceReactiveMySQLConfig dataSourceReactiveMySQLConfig) {
    PoolOptions poolOptions = toPoolOptions(dataSourceRuntimeConfig, dataSourceReactiveRuntimeConfig,
            dataSourceReactiveMySQLConfig);
    MySQLConnectOptions mysqlConnectOptions = toMySQLConnectOptions(dataSourceRuntimeConfig,
            dataSourceReactiveRuntimeConfig, dataSourceReactiveMySQLConfig);
    if (dataSourceReactiveRuntimeConfig.threadLocal.isPresent() &&
            dataSourceReactiveRuntimeConfig.threadLocal.get()) {
        return new ThreadLocalMySQLPool(vertx, mysqlConnectOptions, poolOptions);
    }
    return MySQLPool.pool(vertx, mysqlConnectOptions, poolOptions);
}
 
Example 18
Source Project: quarkus   Source File: MySQLPoolRecorder.java    License: Apache License 2.0 5 votes vote down vote up
private MySQLPool legacyInitialize(Vertx vertx, DataSourceRuntimeConfig dataSourceRuntimeConfig,
        LegacyDataSourceRuntimeConfig legacyDataSourceRuntimeConfig,
        LegacyDataSourceReactiveMySQLConfig legacyDataSourceReactiveMySQLConfig) {
    PoolOptions poolOptions = legacyToPoolOptionsLegacy(legacyDataSourceRuntimeConfig);
    MySQLConnectOptions mysqlConnectOptions = legacyToMySQLConnectOptions(dataSourceRuntimeConfig,
            legacyDataSourceRuntimeConfig, legacyDataSourceReactiveMySQLConfig);
    return MySQLPool.pool(vertx, mysqlConnectOptions, poolOptions);
}
 
Example 19
PgPool sqlClient(int size) {
	PoolOptions options = new PoolOptions();
	PgConnectOptions connectOptions = new PgConnectOptions();
	Matcher matcher = Pattern.compile(PG_URI_MATCHER).matcher(url);
	matcher.matches();
	connectOptions.setDatabase(matcher.group(3));
	connectOptions.setHost(matcher.group(1));
	connectOptions.setPort(Integer.parseInt(matcher.group(2)));
	connectOptions.setUser(user);
	connectOptions.setPassword(pass);
	connectOptions.setCachePreparedStatements(true);
	options.setMaxSize(size);
	return PgPool.pool(vertx, connectOptions, options);
}
 
Example 20
Source Project: vertx-sql-client   Source File: MySQLClientExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void gettingStarted() {

    // Connect options
    MySQLConnectOptions connectOptions = new MySQLConnectOptions()
      .setPort(3306)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);

    // Create the client pool
    MySQLPool client = MySQLPool.pool(connectOptions, poolOptions);

    // A simple query
    client
      .query("SELECT * FROM users WHERE id='julien'")
      .execute(ar -> {
      if (ar.succeeded()) {
        RowSet<Row> result = ar.result();
        System.out.println("Got " + result.size() + " rows ");
      } else {
        System.out.println("Failure: " + ar.cause().getMessage());
      }

      // Now close the pool
      client.close();
    });
  }
 
Example 21
Source Project: vertx-sql-client   Source File: PgClientExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void gettingStarted() {

    // Connect options
    PgConnectOptions connectOptions = new PgConnectOptions()
      .setPort(5432)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);

    // Create the client pool
    PgPool client = PgPool.pool(connectOptions, poolOptions);

    // A simple query
    client
      .query("SELECT * FROM users WHERE id='julien'")
      .execute(ar -> {
      if (ar.succeeded()) {
        RowSet<Row> result = ar.result();
        System.out.println("Got " + result.size() + " rows ");
      } else {
        System.out.println("Failure: " + ar.cause().getMessage());
      }

      // Now close the pool
      client.close();
    });
  }
 
Example 22
Source Project: vertx-sql-client   Source File: MySQLTLSTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPoolFailWithVerifyCaSslMode(TestContext ctx) {
  options.setSslMode(SslMode.VERIFY_CA);
  options.setTrustAll(true);
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  try {
    MySQLPool.pool(vertx, options, new PoolOptions());
  } catch (IllegalArgumentException e) {
    ctx.assertEquals("Trust options must be specified under VERIFY_CA ssl-mode.", e.getMessage());
  }
}
 
Example 23
public DBRest(GreenRuntime runtime, PgConnectOptions options, PoolOptions poolOptions, int pipelineBits, 
		      int maxResponseCount, int maxResponseSize) {
	
	pm = new PoolManager(options, poolOptions);
		
	HTTPResponseService service = runtime.newCommandChannel().newHTTPResponseService(
			                maxResponseCount, 
			                maxResponseSize);
	
	processUpdate = new ProcessUpdate(pipelineBits, service, pm);		
	processFortune = new ProcessFortune(pipelineBits, service, pm);
	processQuery = new ProcessQuery(pipelineBits, service, pm);
	
}
 
Example 24
Source Project: vertx-sql-client   Source File: MySQLPoolImpl.java    License: Apache License 2.0 5 votes vote down vote up
public static MySQLPoolImpl create(ContextInternal context, boolean closeVertx, MySQLConnectOptions connectOptions, PoolOptions poolOptions) {
  QueryTracer tracer = context.tracer() == null ? null : new QueryTracer(context.tracer(), connectOptions);
  VertxMetrics vertxMetrics = context.owner().metricsSPI();
  ClientMetrics metrics = vertxMetrics != null ? vertxMetrics.createClientMetrics(connectOptions.getSocketAddress(), "sql", connectOptions.getMetricsName()) : null;
  MySQLPoolImpl pool = new MySQLPoolImpl(context, new MySQLConnectionFactory(context, connectOptions), tracer, metrics, poolOptions);
  CloseFuture closeFuture = pool.closeFuture();
  if (closeVertx) {
    closeFuture.onComplete(ar -> context.owner().close());
  } else {
    context.addCloseHook(closeFuture);
  }
  return pool;
}
 
Example 25
Source Project: vertx-sql-client   Source File: PgPoolImpl.java    License: Apache License 2.0 5 votes vote down vote up
public static PgPoolImpl create(ContextInternal context, boolean closeVertx, PgConnectOptions connectOptions, PoolOptions poolOptions) {
  QueryTracer tracer = context.tracer() == null ? null : new QueryTracer(context.tracer(), connectOptions);
  VertxMetrics vertxMetrics = context.owner().metricsSPI();
  ClientMetrics metrics = vertxMetrics != null ? vertxMetrics.createClientMetrics(connectOptions.getSocketAddress(), "sql", connectOptions.getMetricsName()) : null;
  PgPoolImpl pool = new PgPoolImpl(context, new PgConnectionFactory(context.owner(), context, connectOptions), tracer, metrics, poolOptions);
  CloseFuture closeFuture = pool.closeFuture();
  if (closeVertx) {
    closeFuture.onComplete(ar -> context.owner().close());
  } else {
    context.addCloseHook(closeFuture);
  }
  return pool;
}
 
Example 26
Source Project: vertx-sql-client   Source File: PgPoolTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRunWithExisting(TestContext ctx) {
  Async async = ctx.async();
  vertx.runOnContext(v -> {
    try {
      PgPool.pool(new PoolOptions());
      ctx.fail();
    } catch (IllegalStateException ignore) {
      async.complete();
    }
  });
}
 
Example 27
Source Project: vertx-sql-client   Source File: PgPoolTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRunStandalone(TestContext ctx) {
  Async async = ctx.async();
  PgPool pool = createPool(new PgConnectOptions(options), new PoolOptions());
  try {
    pool.query("SELECT id, randomnumber from WORLD").execute(ctx.asyncAssertSuccess(v -> {
      async.complete();
    }));
    async.await(4000);
  } finally {
    pool.close();
  }
}
 
Example 28
Source Project: vertx-sql-client   Source File: UnixDomainSocketTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoreSslMode(TestContext context) {
  assumeTrue(options.isUsingDomainSocket());
  client = PgPool.pool(new PgConnectOptions(options).setSslMode(SslMode.REQUIRE), new PoolOptions());
  client.getConnection(context.asyncAssertSuccess(pgConnection -> {
    assertFalse(pgConnection.isSSL());
    pgConnection.close();
  }));
}
 
Example 29
Source Project: vertx-sql-client   Source File: PgPooledConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
public PgPooledConnectionTest() {
  connector = handler -> {
    if (pool == null) {
      pool = PgPool.pool(vertx, new PgConnectOptions(options), new PoolOptions().setMaxSize(1));
    }
    pool.getConnection(handler);
  };
}
 
Example 30
Source Project: vertx-sql-client   Source File: DB2ClientExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void gettingStarted() {

    // Connect options
    DB2ConnectOptions connectOptions = new DB2ConnectOptions()
      .setPort(50000)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);

    // Create the client pool
    DB2Pool client = DB2Pool.pool(connectOptions, poolOptions);

    // A simple query
    client
      .query("SELECT * FROM users WHERE id='julien'")
      .execute(ar -> {
      if (ar.succeeded()) {
        RowSet<Row> result = ar.result();
        System.out.println("Got " + result.size() + " rows ");
      } else {
        System.out.println("Failure: " + ar.cause().getMessage());
      }

      // Now close the pool
      client.close();
    });
  }