Chapter four acquaintance JDBC-

First, what is the connection pool

Before we manipulate when using jdbc database for each CRUD operations must create a database connection object, plain JDBC database connection using the DriverManager to acquire, establish a connection to the database each time in the Connection is loaded into memory, and then verify the user name and password to spend time around 0.05s ~ 1s. Every CRUD operation can be connected to a database, and then perform the complete disconnect. This way will consume a lot of resources and time. Connection resources database has not been well re-use, while if there are hundreds or even thousands of people online, frequent database connection operation will take up a lot of system resources, serious and even cause the collapse of the server.

In order to solve the problems set forth above, we propose the concept of database connection pool.

  • Pool containers holding object
  • Connection pooling save the database connection container object
  • Action
    to create an object of a certain number of initialization. When removed from the pool requires a free object directly, not directly freed after use object, but the object and then into the next tank in order to facilitate the requested object can be directly reused . Pool technology advantage is that you can eliminate delays caused by objects that are created to improve system performance .
  • Database connection pool
    database connection pooling basic idea is to create a "buffer pool" for the database connection. Connected in advance into a certain number of objects in the buffer pool, establish a database connection when needed, simply remove the "pool" of one, then put it back after use. We can be prevented by setting the maximum number of connections endless pool system is connected to the database, you can ﹑ number of connections through the use of management mechanism to monitor the database connection pool, Development, provide the basis for system testing and performance tuning.

Reference schematic connection pool:

Connection pool is a container which stores the limited connection object (Connection), each time we want to java program on a Connection object can simply removed from the connection pool database connections CURD operation. When the java program runs to put the connection object is returned to the pool. Object connection pool is stored in the form of a linked list, the Connection object every time we are out in the head, the return of the object at the end.

Pool connection properties:

Set reasonable connection pool property, will improve the performance of the connection pool

  1. Required when connecting to the database four factors
    drive name, address database, user name, password
  2. Initialization connections
    initialization, the number of connection pool to create a Connection object
  3. Maximum number of connections
    number of connection pool Connection object which stores up
  4. Minimum number of connections
    connecting a plurality of memory cell among the at least have less Connection object
  5. The maximum idle time
    if a connection object is acquired, there is no action within a specified time, it will automatically release link
  6. The maximum waiting time
    within the specified time, trying to get a connection, if beyond the specified time, it will prompt acquisition failure

Second, the use of the connection pool

Connection pooling is javax.sql.DataSource use the interface to indicate the connection pool, DataSource and jdbc, just as only provides an interface that is provided by a third party organization

1. Common connection pool

  • DBCP
    the Spring recommended, Tomcat data source is used DBCP
  • C3P0
    C3P0 is an open source JDBC connection pool, which is published in the lib directory along with Hibernate
    from 2007 has not been updated, and relatively poor performance.
  • Druid
    Alibaba provides connection pooling - Druid - best known as connection pooling, it contains in addition to these, and many more features.

2. Use connection pooling and connection pooling difference NA

  • Obtaining different
    traditions:

    Connection conn = DriverManager.getConnection(url.userName,pwd);

    Connection Pooling:

    Conneciton conn = DataSource对象.getConnection();
  • Releasing resources of different
    traditional: conn.Close and disconnected from the database ();
    connection pool: the database connection object is connected back to the pool, to the next person may also be used

3. The connection pool operations

Mainly learn how to create a DataSource object, then get a Connection object from the DataSource object. These are third-party providers offer us better used directly on the line. After acquiring the connection object, the rest of the operation is the same as before. Different database connection pool, is not the same on the creation DataSource.

1.DBCP
  1. In connection pool used in the project we first need to import the jar package
  2. In connection pool used in the project to obtain the connection, connection pool data acquisition source, obtaining a connection object via a data source
public static void main(String[] args) throws Exception {
        String url = "jdbc:MySQL://localhost:3306/jdbc_db?serverTimezone=UTC&characterEncoding=utf-8&rewriteBatchedStatements=true";
        String user = "root";
        String pwd = "15160673718wen";
        String driver = "com.mysql.cj.jdbc.Driver";

        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driver);
        ds.setUsername(user);
        ds.setPassword(pwd);
        ds.setUrl(url);
        
        Connection conn = ds.getConnection();
        String sql = "select * from stu;";
        
        Statement st = conn.createStatement();
        ResultSet res = st.executeQuery(sql);
        while(res.next()) {
            int id = res.getInt("id");
            int age = res.getInt("age");
            String name = res.getString("name");
            System.out.println(id + " " + name + " " + age);
        }
        
        JDBCUtil.close(conn, st, res);
    }

The above code simply using DBCP example, we can use the same set the maximum number of connections, etc. ds function, then we can encapsulate the code before we write them tools.

2.druid

druid basically compatible DBCP, operating with DBCP is very similar, but the performance is much better than DBCP

4. Read the configuration file

Before our code is written directly user name, password, url in java code, even if we have drawn them to the tools we already use a lot of convenience. But this is a bad way, this is not conducive to the maintenance of late, is also not conducive to the deployment server. Because every time we need to enter the code to modify the content, so that those who are not familiar with our project code it is easy to mistakenly changed our code, leading to Ben collapse of the project. So, we need to separate these elements extracted a written profile

1. Writing the configuration file

We will generally be written in the database configuration file db.properties, the interior is in the form of key-value store. And we generally placed in the configuration file in development Resource (Source Folder) Folder which

    userName=root
    password=1234
2.java reads the configuration file
public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        InputStream in = new FileInputStream("resource/db.properties");
        properties.load(in);
        System.out.println(properties);
        System.out.println(properties.get("user"));
        System.out.println(properties.get("url"));
        System.out.println(properties.get("pwd"));
    }
3. rewrite DBCP

DBCP reads the configuration file we need to press a certain format to write the configuration file

Profiles:

url=jdbc:MySQL://localhost:3306/jdbc_db?serverTimezone=UTC&characterEncoding=utf-8&rewriteBatchedStatements=true
username=root
password=123456
driverClassName=com.mysql.cj.jdbc.Driver

Loading a configuration file:

static {
        try {
            Properties p = new Properties();
            InputStream in = new FileInputStream("resource/db.properties");
            p.load(in);
            ds = BasicDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            
            e.printStackTrace();
        }
    }

Only need to use the Druid

ds = BasicDataSourceFactory.createDataSource(p);

Replaced by:

ds = DruidDataSourceFactory.createDataSource(p);

Third, the summary

jdbc learned that basically finished school, but in front of several articles of the code can continue the reconstruction, the previous code structure is unreasonable. But I'm tired, I do not write reconstruction. JDBC part on this end of it!

Guess you like

Origin www.cnblogs.com/ThinMoon/p/12323195.html