jdbc tomcat pool setting
在tomcat 設定tomcat jdbc pool需要作以下這幾件事情
1.在tomcat目錄下找到lib資料夾將mysql.jar(https://mvnrepository.com/artifact/mysql/mysql-connector-java)丟進去2.配置web.xml相關參數請看https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes
3.配置context.xml
4.設定連結資料庫的LocalhostConnection檔
另外要自己件資料庫喔不然連不上(廢話)
設置web.xml
Resource需設置在GlobalNamingResources內
<GlobalNamingResources>
<Resource
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306"
connectionProperties="characterEncoding=utf8;useUnicode=true;autoReconnect=true"
name="jdbc/localhost"
username="root"
password="1234"
minIdle="1"
initialSize="1"
maxIdle="40"
maxActive="50"
maxWait="30000"
minEvictableIdleTimeMillis="30000"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
jmxEnabled="true"
logAbandoned="false"
removeAbandoned="true"
removeAbandonedTimeout="120"
testOnBorrow="true"
testOnReturn="false"
testWhileIdle="true"
timeBetweenEvictionRunsMillis="5000"
type="javax.sql.DataSource"
validationInterval="60000"
validationQuery="SELECT 1"
validationQueryTimeout="10"
/>
</GlobalNamingResources>
設置context.xml
<Context>
<ResourceLink global="jdbc/localhost" name="jdbc/localhost" type="javax.sql.DataSource" />
</Context>
設置取得連線LocalhostConnection.java檔
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class LocalhostConnection {
static public Connection getConnection() throws NamingException, SQLException {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/localhost");
Connection con = ds.getConnection();
con.setCatalog("mysql");
return con;
}
}
留言
張貼留言