Druid数据库连接池
Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池
Druid的功能
- 替换DBCP和C3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
- 可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
- 数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
- SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
- 扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter机制,很方便编写JDBC层的扩展插件。
所需jar包
druid-1.0.9.jar
mysql-connector-java-5.1.37-bin.jar
链接:https://pan.baidu.com/s/1jGO-JdFqtdD6JktiPtp-SQ
提取码:i7vk
开始
-
将上述jar包导入项目中
-
在config资源文件夹中新建druid.properties配置文件,修改所需配置
########DBCP配置文件########## #驱动名 driverClassName=com.mysql.jdbc.Driver #url url=jdbc:mysql://127.0.0.1:3306/mybase #用户名 username=root #密码 password=root #初试连接数 initialSize=3 #最大活跃数 maxTotal=15 #最大idle数 maxIdle=15 #最小idle数 minIdle=3 #最长等待时间(毫秒) maxWaitMillis=5000 #程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow) #removeAbandoned=true removeAbandonedOnMaintenance=true removeAbandonedOnBorrow=true #连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒) removeAbandonedTimeout=5
-
新建DruidUtil.java工具类
public class DruidUtil { private static Properties prop = new Properties(); private static DataSource dataSource; static{ FileInputStream fis; try { //通过文件流读取配置文件 fis = new FileInputStream("config/druid.properties"); prop.load(fis); //新建数据库连接池 dataSource = DruidDataSourceFactory.createDataSource(prop); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } //获取连接 public static Connection getConnection(){ Connection conn = null; try { conn = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return conn; } }
-
测试获取的连接是否可用,使用JUnit4:右键点击工程名 -> Bulid Path -> Add Liblraries -> JUnit
@Test public void test(){ System.out.println(getConnection()); }
-
如果出现以下结果,说明获取连接成功