Dynamic database pool configuration with Vert.x SQL Client
source link: https://vertx.io/blog/dynamic-db-pool-config-with-sql-client/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Dynamic database pool configuration with Vert.x SQL Client
Vert.x SQL Client provides since Vert.x 4.1.1 connection creation load balancing.
You can create a pool with a list of connect options that the pool uses with a round robin policy when it needs to create a connection.
List<PgConnectOptions> servers = getListOfServers();
PgPool pool = PgPool.create(vertx, servers);
Load balancing is in fact an helper in front of a more powerful feature:
interface Pool {
....
Pool connectionProvider(Function<Context, Future<SqlConnection>> provider);
....
}
The connectionProvider
is called by the pool when it needs to create a new connection, here is a trivial usage:
ConnectionFactory factory = new PgDriver().connectionFactory(vertx, connectOptions);
pool.connectionProvider(ctx -> {
return factory.connect(ctx);
});
Since the provider is asynchronous, it can obviously be abused to provide dynamic pool configuration.
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);
});
});
Important caveat, when the connection factory becomes useless (e.g because of a new configuration) it must be closed to release its resources.
The SQL client does not provide out of the box such feature because of the above caveat: it is difficult to determine when
the factories needs to be disposed. Instead we expose the connectionProvider
to allow application implement it trivially since each
application know best how and when release the resources.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK