Tomcat 在 7.0 之前的版本都是使用 commons-dbcp 作爲鏈接池的實現,可是 dbcp 飽受詬病,緣由有:java
爲此,Tomcat 從 7.0 開始引入一個新的模塊:Tomcat jdbc poolmysql
tomcat jdbc pool 可在 Tomcat 中直接使用,也能夠在獨立的應用中使用。sql
Tomcat 中直接使用的方法:apache
數據源配置:tomcat
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" testWhileIdle="true" testOnBorrow="true" testOnReturn="false" validationQuery="SELECT 1" validationInterval="30000" timeBetweenEvictionRunsMillis="30000" maxActive="100" minIdle="10" maxWait="10000" initialSize="10" removeAbandonedTimeout="60" removeAbandoned="true" logAbandoned="true" minEvictableIdleTimeMillis="30000" jmxEnabled="true" jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" username="root" password="password" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/mysql"/>
異步獲取鏈接的方法:安全
Connection con = null; try { Future < Connection > future = datasource.getConnectionAsync(); while(!future.isDone()) { System.out.println("Connection is not yet available. Do some background work"); try { Thread.sleep(100); //simulate work }catch (InterruptedException x) { Thread.currentThread().interrupted(); } } con = future.get(); //should return instantly Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from user");
在獨立的應用中使用:併發
import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.PoolProperties; public class SimplePOJOExample { public static void main(String[] args) throws Exception { PoolProperties p = new PoolProperties(); p.setUrl("jdbc:mysql://localhost:3306/mysql"); p.setDriverClassName("com.mysql.jdbc.Driver"); p.setUsername("root"); p.setPassword("password"); p.setJmxEnabled(true); p.setTestWhileIdle(false); p.setTestOnBorrow(true); p.setValidationQuery("SELECT 1"); p.setTestOnReturn(false); p.setValidationInterval(30000); p.setTimeBetweenEvictionRunsMillis(30000); p.setMaxActive(100); p.setInitialSize(10); p.setMaxWait(10000); p.setRemoveAbandonedTimeout(60); p.setMinEvictableIdleTimeMillis(30000); p.setMinIdle(10); p.setLogAbandoned(true); p.setRemoveAbandoned(true); p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"); DataSource datasource = new DataSource(); datasource.setPoolProperties(p); Connection con = null; try { con = datasource.getConnection(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from user"); int cnt = 1; while(rs.next()) { System.out.println((cnt++) + ". Host:" + rs.getString("Host") + " User:" + rs.getString("User") + " Password:" + rs.getString("Password")); } rs.close(); st.close(); } finally { if(con != null) try { con.close(); } catch(Exception ignore) {} } } }