Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tomcat: 1 war, deployed 2x, 2 configs

Simplified situation:

  • I have 1 Tomcat container and 1 WAR which uses a database.
  • The database configuration sits in a properties file (in the war).
  • I deployed the WAR 2 times, one webapp on contextpath /a and one webapp on contextpath /b.
  • Both webapps now point to the same database (same cfg).

What I want is that each webapp points to a different database. So, the webapp on /a points to database A and the the webapp on /b points to database B.

How would you solve this? (without splitting the war itself)

like image 347
codesmith Avatar asked Dec 08 '17 10:12

codesmith


2 Answers

You can do it by Tomcat's context.xml configuration without splitting your code.

You can define two context for example /a and /b and two different global data sources "sharedDataSourceA" and "sharedDataSourceB". You can bind different global data sources to these contexts with same name like "appDataSource".

<GlobalNamingResources>
  ...
  <Resource name="sharedDataSourceA"
            global="sharedDataSourceA"
            type="javax.sql.DataSource"
            factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
            alternateUsernameAllowed="true"
            username="bar"
            password="barpass"
            ...
<Resource name="sharedDataSourceB"
            global="sharedDataSourceB"
            type="javax.sql.DataSource"
            factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
            alternateUsernameAllowed="true"
            username="bar"
            password="barpass"
            ...
  ...
</GlobalNamingResources>

<Context path="/a"...>
  ...
  <ResourceLink
            name="appDataSource"
            global="sharedDataSourceA"
            type="javax.sql.DataSource"
            factory="org.apache.naming.factory.DataSourceLinkFactory"
            username="foo"
            password="foopass"
  ...
</Context>
<Context path="/b"...>
  ...
  <ResourceLink
            name="appDataSource"
            global="sharedDataSourceA"
            type="javax.sql.DataSource"
  ...
</Context>

Then in your code you can bind datasource to "appDataSource" by jndi lookup. Deploy the same war to /a and /b . They will work on different databases.

like image 56
Mehmet Sunkur Avatar answered Sep 26 '22 02:09

Mehmet Sunkur


You could get the current context programmatically and configure the datasource according to the obtained value. For example using javax.servlet.ServletContext.getContextPath().

You could also load a properties file according to context name.

like image 24
LMC Avatar answered Sep 24 '22 02:09

LMC