前几天有朋友问Tomcat 中配置多数据源,做了个小例子。
数据源: 本机MySQL的2个数据库 mydb1, mydb2
先在Eclipse中建立一个Web项目, 我的叫MyWebApp
在apache-tomcat-5.5.17\conf\Catalina\localhost中,建立名为MyWebApp.xml的文件,在其中指明项目路径和数据源配置,内容如下:
xml 代码
- <Context path="/" docBase="D:/workspaceWTP1.5/MyWebApp/web" debug="99" reloadable="true">
- <Logger className="org.apache.catalina.logger.FileLogger" prefix="dvs." suffix=".txt" timestamp="true"/>
- <Resource
- name="jdbc/mydb1"
- type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- maxIdle="30"
- maxWait="10000"
- username=""
- password=""
- url="jdbc:mysql://localhost/mydb1?autoReconnect=true&useUnicode=true&characterEncoding=utf-8"
- maxActive="100"/>
- <Resource
- name="jdbc/mydb2"
- type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- maxIdle="30"
- maxWait="10000"
- username=""
- password=""
- url="jdbc:mysql://localhost/mydb2?autoReconnect=true&useUnicode=true&characterEncoding=utf-8"
- maxActive="100"/>
- </Context>
然后在MyWebApp项目的WEB-INF/web.xml 中引用这两个数据源
xml 代码
- <resource-env-ref>
- <description>myDB1 Connection</description>
- <resource-env-ref-name>jdbc/mydb1</resource-env-ref-name>
- <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
- </resource-env-ref>
- <resource-env-ref>
- <description>myDB2 Connection</description>
- <resource-env-ref-name>jdbc/mydb2</resource-env-ref-name>
- <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
- </resource-env-ref>
这样就可以在web应用中使用这两个数据源了,可以写个简单的servlet测试
java 代码
- public static final String namespace = "java:comp/env";
- public DataSource getDataSource(String resourceName) throws NamingException {
- InitialContext init = new InitialContext();
- Context ctx = (Context)init.lookup(namespace);
- return (DataSource)ctx.lookup(resourceName);
- }
- private void doService(HttpServletRequest request, HttpServletResponse response) throws IOException, NamingException, SQLException {
- DataSource ds1 = getDataSource("jdbc/mydb1");
- DataSource ds2 = getDataSource("jdbc/mydb2");
- response.getWriter().println("DataSource ds1 is : " + ds1);
- response.getWriter().println("DataSource ds2 is : " + ds2);
- Connection conn1 = ds1.getConnection();
- String sql1 = "select email from users where id = 15";
- response.getWriter().println("email is : " + executeQuery(conn1, sql1));
- Connection conn2 = ds2.getConnection();
- String sql2 = "select product_name from products where id = 1";
- response.getWriter().println("Product Name is : " + executeQuery(conn2, sql2));
- }
其中executeQuery方法就是简单的数据库查询,这里就不详细写了.
如果使用Hibernate也很简单,只要在两个不同的hibernate.cfg.xml文件中分别指定不同的hibernate.connection.datasource就可以了.