连接池
在Java中,连接池使用javax.sql.DataSource接口来表示连接池.
DataSource(数据源)和连接池(Connection Pool)是同一个.
DBCP: Spring框架推荐的
druid: 阿里巴巴的连接池(号称Java语言中性能最好的连接池)
DBCP连接池
1 | package me.cscar.dbcp.util; |
druid连接池
阿里巴巴研发出来的号称Java语言领域性能最高的连接池.
wiki地址:https://github.com/alibaba/druid/wiki
使用起来,类似于DBCP连接池.
方便检测性能/状态.
支持:MySQL,Oracle,DB2,sql Server等.
支持:对配置文件的密码加密.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61package me.cscar.dbcp.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCutil {
private static Properties prs = new Properties();
//private static BasicDataSource bds = null;
private static DataSource dsf = null;
static {
try {
InputStream in = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("db.properties");
prs.load(in);
Class.forName(prs.getProperty("driverClassName"));
//在静态代码块中初始化连接池对象,连接池只需一个即可
//bds = BasicDataSourceFactory.createDataSource(prs);
//druid连接池
dsf = DruidDataSourceFactory.createDataSource(prs);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
//Connection conn = bds.getConnection();
Connection conn = dsf.getConnection();
return conn;
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("数据库链接失败");
}
public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
代码重构
1 | package me.cscar.dbcp.dao.impl; |