Using dynamic Datasource with Tomcat

前提是你 提交于 2019-11-28 04:48:10

问题


I'm creating a series of webservices for my application and i have the need to access a different database based on the serviceCode that is passed as a parameter in the webservice call.

I setup a basic resource with tomcat to access a database like this

<Resource name="jdbc/db_name" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user" password="pass" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://server_ip:3306/db_name"/>

But in this way i have to setup a resource for every database i create on the server, what i wanted, and that i didn't found info ( or didn't understand ), was to be able to set db_name as a variable that is passed at runtime from the webservice, so basically having only one resource and using it dinamically instead of having a resource for every database ( that would require me to start the server for changing the context.xml every time i create a new database)

I access the resource using scalaquery like this

val db = Database.forDataSource(datasource("jdbc/db_name"))

and this is the point where i wanted to be able to dinamically pass the db_name, or define the resource at runtime, is there an alternative way with tomcat/scala or am i forced to add a resource everytime?


回答1:


Define your own Resource. See the Tomcat documentation. You provide an implementation of javax.naming.spi.ObjectFactory. Have it return an appropriate implementation of Context such that looking it up via some name returns a DB connection to that name. In my case the required entry in context.xml looked like this:

<Resource
    name="ldap/Context" // your name, probably something like jdbc/dynamic
    auth="Container"
    type="javax.naming.ldap.LdapContext"
    factory="com.xxxx.ldap.LdapContextFactory"
    // your initialization params here, if any
    >


来源:https://stackoverflow.com/questions/6055357/using-dynamic-datasource-with-tomcat

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