开发者

Using dynamic Datasource with Tomcat

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 a开发者_如何学Goccess 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?


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
    >
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜