Article Directory
Apache commons and open source data source connection pool DBCP
1、Apache commons
Apache Commons is a very useful toolkit to solve various practical common problems . The official website of Apache Commons is introduced.
Here are some toolkit introductions:
Types of | description |
---|---|
BeanUtils | Commons-BeanUtils provides packaging for Java reflection and introspection API |
Betwixt | Betwixt provides services for mapping JavaBeans to XML documents and vice versa. |
Chain | Chain provides the "responsibility chain model" that realizes the complex processing flow of the organization. |
CLI | CLI provides simple API for command line parameters, options, option groups, mandatory options, etc. |
Codec | Codec contains some general encoding and decoding algorithms. Including some voice encoders, Hex, Base64, and URL encoder. |
Collections | Commons-Collections provides a class package to extend and increase the standard Java Collection framework |
Configuration | The Commons-Configuration tool provides reading help for various configurations and reference files. |
Daemon | An alternative mechanism for unix-daemon-like java code |
DBCP | Commons-DBCP provides database connection pool service |
DbUtils | DbUtils is a JDBC helper library, simple resource cleanup code for completing database tasks. |
Digester | Commons-Digester is an XML-Java object mapping tool for parsing XML configuration files. |
Discovery | Commons-Discovery provides tools to locate resources (including classes), and map service/reference names and resource names by using various patterns. . |
HE | Commons-EL provides an interpreter for EL expressions defined in the JSP2.0 specification. |
FileUpload | FileUpload makes it easy to add powerful and high-performance file upload capabilities to your applications and servlets |
HttpClient | Commons-HttpClient provides a framework that can work with HTTP protocol clients. |
I | IO is an I/O toolset |
Jelly | Jelly is an XML-based scripting and processing engine. Jelly draws on the many advantages of JSP designated tags, script engines in Velocity, Cocoon and Xdoclet. Jelly can be used on the command line, Ant or Servlet. |
Jexl | Jexl is an expression language that extends the expression language defined by JSTL by drawing on the experience from Velocity. . |
JXPath | Commons-JXPath provides tools for using Xpath syntax to manipulate JavaBeans conforming to the Java class naming convention. Also supports maps, DOM and other object models. . |
Lang | Commons-Lang provides many common tool class sets, and provides some extended functions of java.lang classes |
Puppet | Commons-Latka is an HTTP functional test package for automated QA, acceptance and attenuation testing. |
Launcher | The Launcher component is a cross-platform Java application loader. Commons-launcher eliminates the need for batch processing or Shell scripts to load Java classes. The original Java class comes from the Jakarta Tomcat 4.0 project |
Logging | Commons-Logging is a package class that implements various logging APIs. |
Math | Math is a lightweight, self-contained mathematical and statistical component that solves many practical problems that are very common but have not appeared in the Java standard language in time. |
Modeler | Commons-Modeler provides a mechanism for modeling MBeans compatible with the JMX specification. |
Net | Net is a network tool set, based on NetComponents code, including FTP client and so on. |
Pool | Commons-Pool provides a common object pool interface, a toolkit for creating modular object pools, and common object pool implementations. |
Primitives | Commons-Primitives provides a smaller, faster and easier-to-use support for basic Java types. Currently, it is mainly for collections of basic types. . |
Validator | commons-validator provides a simple and extensible framework to define validators (validation methods) and validation rules in an XML file. Support the internationalization of verification rules and error messages. |
2. Use open source DBCP to optimize data source design
Two packages are required to use DBCP data source connection in JDBC
- DBCP, such as commons-dbcp2-2.7.0-bin.tar.gz related download link
- The connection pool used, such as commons-pool2-2.8.1-bin.tar.gz related download connection
You can also download if necessary
- Corresponding collections such as commons-collections4-4.4-bin.tar.gz related download link
- commons-logging-1.2-bin.tar.gz rack package
After downloading, add it to the corresponding project module. File-"Project Structure-"Module-"Dependencies
2.1, use DBCP to replace datasource connection pool datasource code
Take a look at the previous code:
public final class JDBCUtils {
private static DataSource datasource;//代理模式的数据源2,实现了DataSource接口
public static Connection getConnect() throws SQLException {
//异常应该抛出
return datasource.getConnection();
}
static{
//使用class.forName()方法一般用于静态代码块,而且该方法注册驱动不依赖具体的类库
try {
//forName进行类的加载时优先加载静态代码块。
Class.forName("com.mysql.cj.jdbc.Driver");
datasource=new DataSource2();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void free(Connection conn, Statement st, ResultSet res) {
try {
if (res != null) //原则1:晚点连接早点释放。原则2:先创建的后释放
res.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
//datasource.free(conn);//重用,将创建的连接不关闭,而是将其回收到连接池
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
We use a simple data source connection pool implementation written by ourselves. Now we use DBCP to change.
Step 1: Create a configuration file (set the basic property information of the connection)
In actual development, we usually create a properties configuration file, and then put the database parameters in the configuration file, which facilitates the management of database parameters, and when the database parameters change, the configuration file can be quickly found and then modified.
If you are not creating a configuration file, then you need to create a property in the code, and then set the database parameters, which is hard to write. Not flexible enough.
第二步,修改数据源的引用和创建
我们只需要修改下面这段代码:
static{
//使用class.forName()方法一般用于静态代码块,而且该方法注册驱动不依赖具体的类库
try {
//forName进行类的加载时优先加载静态代码块。
Class.forName("com.mysql.cj.jdbc.Driver");
datasource=new DataSource2();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
修改为:
static{
//使用class.forName()方法一般用于静态代码块,而且该方法注册驱动不依赖具体的类库
try {
//forName进行类的加载时优先加载静态代码块。
Class.forName("com.mysql.cj.jdbc.Driver");
//datasource=new DataSource2();
InputStream inputs = JDBCUtils.class.getClassLoader().getResourceAsStream("DBCP_Config.properties");
Properties properties = new Properties();
properties.load(inputs);
datasource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
运行代码报错,原因就是我们利用的加载文件的方式是JDBCUtils.class.getClassLoader().getResourceAsStream(),而我们的文件没有放对位置。其路径,我们可用如下方法打印出来。
System.out.println(JDBCUtils.class.getClassLoader().getResource(""));
在将配置文件放到了对应的目录以后运行测试代码
for(int i=0;i<10;i++){
Connection conn = JDBCUtils.getConnect();
System.out.println(conn);
JDBCUtils.free(conn,null,null);
}
报错:
原因:从理解上看是缺少了一个类文件,logging,即缺少了commons-logging-1.2-bin.tar.gz架包。导入以后运行:
从输出上看,我们可对比我们自己实现的dataSource,可以说DBCP自己肯定重写了toString方法。输出的是数据库连接的一些信息。
2.2、总结
- 一,使用DBCP的重点是获取DataSource对象
- 二,使用DBCP不仅可以节约资源,而且可以直接将查询结果封装成对象,方便使用。
- 三,在实际开发中建议使用properties配置文件。