那么,它是一个客户端应用程序?应用程序和数据库通常使用DriverManager#getConnection()获得的连接相互通信?如果是这样,那么您不一定需要JNDI才能使连接池工作.单独的连接池框架已经足够了.例如
C3P0或
Apache Commons DBCP(我建议使用C3P0; DBCP是单线程的).只需用它替换DriverManager#getConnection()即可.
编辑:回复您的评论:
The server would be talking to the database and the clients connect to the server, so I won’t know whether to call this a client application.
我的意思是,一个普通的Java应用程序,它不在Java EE容器内运行.帕斯卡的措辞更好.
Actually I’m a bit confused about how connection pooling works, does each connection run in its own thread? is there any document/book to help me get a better understanding of these concepts vis-a-vis a non pooled connection?
首先,只要达到配置的超时,连接池就会打开一个连接并保持打开状态.连接池使用自己的实现包装/ decorates连接.连接池可以同时打开并保持配置数量的连接.当你调用getConnection()时,它会立即给你一个已打开的连接.当您在连接上调用close()时,它会将连接放回池中以供将来请求使用.这意味着您仍然必须以通常的方式编写JDBC代码:在尽可能短的范围内获取并关闭Connection,Statement和ResultSet.在finally块中关闭它们.如果您的JDBC代码已经写得很好,实际上只需要替换DriverManager#getConnection().由于您应该在同一个方法块中打开和关闭Connection,它通常会在同一个线程中运行.在您的代码调用Connection上的close()之前,连接池将担心同时没有其他线程获取Connection.
你可以在here找到一篇很好的文章来了解连接池如何在引擎盖下工作(注意:不要将它用于生产,也不要进一步生成它,这只是为了得到完整的想法).对于实际工作,请使用现有的彻底开发且强大的连接池框架.