我有一个用例,其中我使用memcache来缓存数据库中的某些结果。我将查询本身用作键,值将是CachedRowSetImpl类型,该序列将结果集序列化。要形成查询,我需要使用PreparedStatement,而这又需要一个到数据库的连接对象。由于超过一半的时间用于建立连接,因此这使缓存的全部目的无效。有什么解决办法吗?还是我必须使用其他方法来缓存结果?

最佳答案

为避免每次都建立连接,请使用连接池,例如c3p0。您将连接池配置为使用Postgres,用户名swaldman和passwordComboPooledDataSource

// in constructor
cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("swaldman");
cpds.setPassword("test-password");


当您需要JDBC连接时,只需使用:

Connection connection = cpds.getConnection();


还有其他连接池,例如DBCP,以类似的方式设置。

08-04 21:14