mercredi 17 septembre 2014

Initializing C3P0 pool at startup using Spring

As of C3P0 version 0.9.5-pre8, the pool manager will not be initialized until the first time getConnection() is called on the DataSource.

I wrote an application server that receives and processes commands. Processing the commands generally requires accessing a database, especially for the first received commands. The problem was the application server took time to process the first command because it was the first time the getConnection() method was called, and therefore the sending client triggered a timeout and removed the "unresponsive" application server from its list of available application servers. This is one use case where one would like to initialize as much as possible at application startup.

If you use Spring JdbcTemplate, one option is to force initialization of the exception translator as follows (note the second argument of the JdbcTemplate constructor):

@Repository("myRepository")  
public class MyRepositoryImpl implements MyRepository {
 
     private JdbcTemplate jdbcTemplate;

     @Autowired  
     public void setDataSource(DataSource dataSource) {  
          jdbcTemplate = new JdbcTemplate(dataSource, false);  
     }

}  

Initializing the exception translator requires accessing the database and therefore at some point will call the getConnection() method which will trigger pool manager initialization.

The main idea is just to call getConnection() at startup to trigger pool manager initialization. Therefore, as long as you can manage to get the getConnection() method called at startup, you are done.

If you don't use Spring but use Java 7, an empty try-with-resource block will be enough:

try(Connection conn = dataSource.getConnection()) {}

Aucun commentaire:

Enregistrer un commentaire