数据库连接池

来源:互联网 发布:恋夜秀场源码 编辑:程序博客网 时间:2024/06/02 00:18

1.原理
应用初始化阶段根据driver(Class.forName(driver)),
url,username,password(DriverManager.getConnection(url, username,password)
创建多个连接,然后将连接添加到LinkedList中,
当需要conn时,从List中获取getConnection()单个conn (list.removeFirst())
当调用conn.close()时,将conn返回到List中
当min不够用时,连接池中新建connection,但不超过max
当连接数超过max时,排队

这里写图片描述

2.开源连接池
DBCP 数据库连接池
C3P0 数据库连接池

3.tomcat连接池
在META-INF目录下新建context.xml文件配置连接池

<Context>   <Resource       name="jdbc/datasource"       auth="Container"       type="javax.sql.DataSource"       username="root"       password="XDP"       driverClassName="com.mysql.jdbc.Driver"       url="jdbc:mysql://localhost:3306/jdbcstudy"       maxActive="8"       maxIdle="4"/></Context>将mysql驱动包

添加到tomcat的lib目录下
在JNDI容器中获取连接池
(tomcat会将连接池发布到JNDI容器中,JNDI容器以 名称-资源 形式保存资源)

Context initCtx = new InitialContext();Context envCtx = (Context) initCtx.lookup("java:comp/env");dataSource = (DataSource)envCtx.lookup("jdbc/datasource");
原创粉丝点击