Using a dynamic data source with Tomcat

I am creating a series of web services for my application, and I need to access another database based on the service code that is passed as a parameter in the webservice call.

I am setting a base resource using 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 had to set up a resource for each database created on the server, what I wanted, and that I did not find the information (or did not understand), was to set db_name as a variable that is passed at run time from webservice, so basically has only one resource and uses it dynamically, instead of having a resource for each database (for which I need to start the server to change 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 moment when I would like to dynamically pass the name db_name or define a resource at runtime, is there an alternative way with tomcat / scala or am I forced to add a resource every time?

+3
source share
1 answer

Define your own resource. See the Tomcat documentation. You provide an implementation of javax.naming.spi.ObjectFactory. Ask him to return the appropriate implementation of the Context, so searching for it through some name returns a DB connection with 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
    >
+4
source

Source: https://habr.com/ru/post/1693685/


All Articles