Dynamic database pool configuration with Vert.x SQL Client

Since Vert.x 4.1.1, the SQL Client pro­vides con­nec­tion cre­ation load bal­anc­ing.

You can cre­ate a pool with a list of con­nect op­tions that the pool uses with a round robin pol­icy when it needs to cre­ate a con­nec­tion.

List<PgConnectOptions> servers = getListOfServers();

PgPool pool = PgPool.create(vertx, servers);

Load bal­anc­ing is ac­tu­ally a helper in front of a more pow­er­ful fea­ture:

interface Pool {
  ....
  Pool connectionProvider(Function<Context, Future<SqlConnection>> provider);
  ....
}

The connectionProvider is called by the pool when it needs to cre­ate a new con­nec­tion. Here is a triv­ial ex­am­ple:

ConnectionFactory factory = new PgDriver().connectionFactory(vertx, connectOptions);
pool.connectionProvider(ctx -> {
  return factory.connect(ctx);
});

Since the provider is asyn­chro­nous, it can be used to pro­vide dy­namic pool con­fig­u­ra­tion.

pool.connectionProvider(ctx -> {
  Future<PgConnectOptions> fut = retrieveOptions();
  return fut.compose(connectOptions -> {
    // Do not forget to close later
    ConnectionFactory factory = new PgDriver().connectionFactory(vertx, connectOptions);
    return factory.connect(ctx);
  });
});

Im­por­tant caveat: when the con­nec­tion fac­tory be­comes use­less (e.g be­cause of a new con­fig­u­ra­tion) it must be closed to re­lease its re­sources.

The SQL client does not pro­vide this fea­ture out of the box be­cause of this caveat. It is dif­fi­cult to de­ter­mine when the fac­to­ries need to be dis­posed. In­stead, we ex­pose the connectionProvider to allow ap­pli­ca­tions to im­ple­ment it triv­ially since each ap­pli­ca­tion knows best how and when to re­lease the re­sources.

Next post

Eclipse Vert.x 4.2.0.Beta1 released!

The first beta of the upcoming Vert.x 4.2 has just been released. We consider it feature complete and invite the community to test it.

Read more
Previous post

Eclipse Vert.x 4.1.2 released!

Eclipse Vert.x version 4.1.2 has just been released. It fixes quite a few bugs that have been reported by the community and provides a couple of features

Read more
Related posts

Unit and Integration Tests

Let’s refresh our mind about what we developed so far in the introduction to vert.x series. We forgot an important task. We didn’t test the API.

Read more

Using the asynchronous SQL client

Finally, back... This post is the fifth post of the introduction to vert.x blog series, after a not-that-small break. In this post we are going to see how we can use JDBC in a vert.x application.

Read more

Building services and APIs with AMQP 1.0

Microservices and APIs are everywhere. Everyone talks about them, presentation slides are full of them ... some people are actually even building them.

Read more