数据库连接池
1.连接池概念:
2.自己写一个连接池,并使自己的连接池在conn调用close方法时可以将连接直接返回池中:
public class MyPool implements DataSource {
private static List<Connection> pool = new LinkedList<Connection>();
static{
try{
Class.forName("com.mysql.jdbc.Driver");
for(int i=0;i<5;i++){
Connection conn = DriverManager.getConnection("jdbc:mysql:///day11","root","root");
pool.add(conn);
}
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public Connection getConnection() throws SQLException {
if(pool.size()==0){
for(int i=0;i<3;i++){
Connection conn = DriverManager.getConnection("jdbc:mysql:///day11","root","root");
pool.add(conn);
}
}
final Connection conn = pool.remove(0);
//--利用动态代理改造close方法
Connection proxy = (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn.getClass().getInterfaces()
, new InvocationHandler(){
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
if("close".equals(method.getName())){
//对于想要改造的close方法,我们自己写
retConn(conn);
return null;
}else{
//对于不想改造的方法调用被代理者身上相同的方法
return method.invoke(conn, args);
}
}
});
System.out.println("获取了一个连接,池里还剩余"+pool.size()+"个连接");
return proxy;
}
private void retConn(Connection conn){
try {
if(conn!=null && !conn.isClosed()){
pool.add(conn);
System.out.println("还回了一个连接,池里还剩余"+pool.size()+"个连接");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
...
//其余待实现的方法
3.开源数据库连接池:
(1)DBCP
BasicDataSource dataSource = new BasicDataSource();
String path = this.getClass().getClassLoader().getResource("dbcp.properties").getPath();
Properties prop = new Properties();
prop.load(new FileInputStream(path));
DataSource dataSource = BasicDataSourceFactory.createDataSource(prop);
配置文件属性:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc
username=root
password=
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
(2)C3P0
方法一:
ComboPooledDataSource source = new ComboPooledDataSource();
source.setDriverClass("com.mysql.jdbc.Driver");
source.setJdbcUrl("jdbc:mysql:///day11");
source.setUser("root");
source.setPassword("root");
方法二:
ComboPooledDataSource dataSource = new ComboPooledDataSource();
ComboPooledDataSource dataSource = new ComboPooledDataSource("mySoruce");
在类加载目录下创建名称为c3p0-config.xml的配置文件,并在其中中配置:
<?xml version="1.0"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property >
<property name="jdbcUrl">jdbc:mysql:///Day12</property >
<property name="user">root</property>
<property name="password">root</property>
</default-config>
<!-- This app is massive! -->
<named-config name="mySoruce">
<property name="driverClass">com.mysql.jdbc.Driver</property >
<property name="jdbcUrl">jdbc:mysql:///Day12</property >
<property name="user">root</property>
<property name="password">root</property>
</named-config>
</c3p0-config>
driverClass
jdbcUrl
user
password
acquireIncrement:当连接池中已经没有连接时,连接池自动获取连接时一次获取的连接个数。
initialPoolSize:连接池初始化时,获取连接的个数。
maxPoolSize:连接池可以保有的最大的连接的数量。
maxIdleTime:当连接空闲多久时释放连接。如果该时间值设置为0,表示从不释放连接。
minPoolSize:连接池应该保有的最小的连接的数量。
4.tomcat内置的数据源:tomcat内置了DBCP数据源
<1>在tomcat的安装目录下的lib目录下导入数据库驱动包
<2>在Context中配置数据源,有五个位置可以配置,参考tomcat文档
~在conf/context.xml爸爸Context中配置,这个配置将被tomcat的所有web应用共享
In the $CATALINA_BASE/conf/context.xml file: the Context element information will be loaded by all webapps.
~在conf/Catalina/localhost/context.xml,这个配置将被当前虚拟主机所共享
In the $CATALINA_BASE/conf/[enginename]/[hostname]/context.xml.default file: the Context element information will be loaded by all webapps of that host.
~在conf/Catalina/localhost/XXXXXX.xml,这是配置web应用的对外访问路径,这个配置只对当前web应用起作用
In individual files (with a ".xml" extension) in the $CATALINA_BASE/conf/[enginename]/[hostname]/ directory. The name of the file (less the .xml extension) will be used as the context path. Multi-level context paths may be defined using #, e.g. foo#bar.xml for a context path of /foo/bar. The default web application may be defined by using a file called ROOT.xml.
~在web应用的META-INF目录下创建context.xml这个配置只对当前web应用起作用
Only if a context file does not exist for the application in the $CATALINA_BASE/conf/[enginename]/[hostname]/, in an individual file at /META-INF/context.xml inside the application files. If the web application is packaged as a WAR then /META-INF/context.xml will be copied to $CATALINA_BASE/conf/[enginename]/[hostname]/ and renamed to match the application's context path. Once this file exists, it will not be replaced if a new WAR with a newer /META-INF/context.xml is placed in the host's appBase.
~在conf/servler.xml的Host标签下配置Context标签
Inside a Host element in the main conf/server.xml.
<3>在Cotext中配置:
<Resource name="mySource" ---在数据源创建好以后绑定到jndi容器中时使用的名字
auth="Container"
type="javax.sql.DataSource" ---当前对象的类型,默认就是数据源
username="root" --- 数据库用户名
password="root" --- 数据库密码
driverClassName="com.mysql.jdbc.Driver" ---数据库驱动名
url="jdbc:mysql:///db_name" --- 数据库连接信息
maxActive="8" --- 最大连接数
maxIdle="4"/> --- 最大空闲连接数
<4>在程序中获取数据源:
Context context = new InitialContext();
Context envCtx = (Context)context.lookup("java:comp/env");
DataSource datasource = (DataSource) envCtx.lookup("mySource");