Ivan Gerken
Ivan Gerken

Reputation: 914

MySQL DataSource with connection pooling, setting URL at run-time

I have a Java service running in Tomcat that makes some tens of short database reads from a MySQL database per second. Obviously, I need a DataSource with connection pooling. I obtain the connection string from a secure storage at run-time, so the most known way of obtaining a DataSource instance via JNDI from container does not seem to be applicable in my case.

I found 2 possible solutions and I'm hesitating between them.

  1. Creating a MysqlConnectionPoolDataSource instance in my code - appeals to me more because it is not coupled with a specific container. However, this post claims that this is totally wrong.
  2. Using Tomcat's DataSource and PoolProperties from org.apache.tomcat.jdbc.pool as in the "Plain Ol' Java" example

Upvotes: 0

Views: 891

Answers (1)

malaguna
malaguna

Reputation: 4233

Or a third way, that basically is to use Apache Commons Database Pooling AKA commons-pooling, that lets you create database pools programatically:

private BasicDataSource pool = new BasicDataSource();

pool.setDriverClassName(driver);
pool.setUrl(url);
pool.setUsername(user);
pool.setPassword(pass);
pool.setInitialSize(size);

After this, you can use pool to do what you want. Of course you can use other DataSource implementations.

This way you don't get coupled to tomcat, neither you need container configuration files.

Upvotes: 2

Related Questions