Multiple Data sources for C3P0

坚强是说给别人听的谎言 提交于 2019-12-11 03:57:40

问题


I am developing a tool that receives different connection parameters to test values in different databases (a plugin for Nagios in jNRPE that keeps an open connection to different databases). Because the configuration is dynamic (there could be more databases or they can be removed) I cannot have a configuration file.

I want to know if I should have an instance of C3P0 per database or can I use the same instance and just change the URL each time I ask for a connection?

The code is at github: https://github.com/angoca/db2-jnrpe/blob/master/src/main/java/com/github/angoca/db2_jnrpe/database/pools/c3p0/DBCP_c3p0.java

If not, how can I get multiple pool for multiple databases dynamically?


回答1:


You'll need a different c3p0 DataSource for each JDBC url. A Connection pool must contain homogeneous Connections: all checked out Connections must be equivalent from a client's perspective. If Connections from multiple databases were included in the same pool, clients would have no way of specifying or knowing which db they were communicating with.

(If you are replicating, say, a read-only DB and you really want Connections from multiple sources to live in a single pool, because they are guaranteed to be equivalent from a client's point of view, you could do that by defining a custom, unpooled DataSource that round-robined or randomly chose a replicant, and then pooling the DataSource via c3p0's DataSources factory.)

It is very easy to dynamically create and configure c3p0 DataSources. See example code here.

If you capture your dynamic config as a map of c3p0 property names to values, there's also an alternative, more concise way to get a DataSource with that configuration.



来源:https://stackoverflow.com/questions/26785842/multiple-data-sources-for-c3p0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!