如果每个查询100毫秒适合您,那么您不需要连接池.如果您需要小于20毫秒的查询,则重用连接至关重要.
如果您的驱动程序支持自己的连接池,我建议您使用它(如果它已经不适合您).只有当你想要更好地控制如何汇集连接时,你才可以使用一个额外的库(我自己从未找到过很好的用途)
注意:您无需使用池来重用连接.
重用连接的一种简单方法是使用一个持久连接(具有适当的线程安全防护)如果您的查询很少,这可能就是您所需要的.
如果您希望能够同时执行查询并且只有几个将执行查询的线程,则可以在ThreadLocal字段中存储连接.
如果您想要多个连接,并且您有更多线程可以执行查询而不是您想要的连接,请使用池.
对于ThreadLocal模型,您可以这样做
public static final ThreadLocal CONNECTION = new ThreadLocal() {
public Connection initialValue() {
LOG.info(Thread.currentThread()+": created a connection.");
return createConnection();
}
};
如果要控制连接的清理方式.
private static final Map connections = new ConcurrentHashMap();
public static final ThreadLocal CONNECTION = new ThreadLocal() {
public Connection initialValue() {
LOG.info(Thread.currentThread()+": created a connection.");
Connection conn = createConnection();
connections.put(Thread.currentThread(), conn);
return conn;
}
};
public static void cleanUp() {
for(Map.Entry entry: connections.entrySet()) {
Thread t = entry.getKey();
if (!t.isAlive()) {
LOG.info(t+": closed a connection.");
connections.remove(t);
entry.getValue().close();
}
}
}
如果您担心获得死连接,可以在返回之前覆盖ThreadLocal的get()以测试连接.