Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

scala - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    >

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...