做一個緩沖區(調度室)來解決,不要直接進行物理連接數,稱為DataSource 。
實現方法:
1.簡單實現
2.pooled池化實現
3.分布式實現
pooled池化實現方法:
1.DBCP:實現JDBC2.0或更高版本,標準實現。
2.C3P0。
3.proxool:在外層包裝一層池。
直接使用容器中帶過來的連接池技術。
配置TomCat,使用了一個JNDI技術(目錄訪問協議)。
1.配置:
<!-- The contents of this file will be loaded for each web application -->
<Context docBase="CRMDemo"
???????? privileged="true" antiResourceLocking="false" antiJARLocking="false">
?<Resource name="jdbc/CRMDemo" auth="Container" class="org.apache.commons.dbcp.BasicDataSource"
? type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
? url="jdbc:mysql://localhost:3306/test" username="root" password="root"
? maxActive="10" maxIdle="5" removeAbandoned="true" maxWait="300" />
</Context>
docBase是工程項目的名稱。
name是自己取的,在程序中需要調用到。
一定要開啟服務器才能運行有效。
2.實現連接:
?public static Connection getConnection() throws NamingException, SQLException {
??Context initContext = new InitialContext();
??// 注意: 以下寫法只適用于tomcat(java:/comp/env).
??DataSource dataSource = (DataSource) initContext.lookup("java:/comp/env/jdbc/CRMDemo");
??Connection conn = dataSource.getConnection();
??return conn;
?}
在此的參數是固定的,每個服務器都有相應的參數。
其中調用了在配置文件中的名字,請注意!