简体   繁体   English

如何使用连接池

[英]How to use connection pooling

I am new in connection pooling.I have a created a connection pool in mysql that adds five connections.Now i want to know what is the application of connection pooling,ie after creating that pool how to use that.. i am pasting my code here 我是连接池的新手。我在mysql中创建了一个连接池,该连接池添加了五个连接。现在我想知道连接池的应用是什么,即在创建该池后如何使用它。这里

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

import com.mysql.jdbc.Connection;

class ConnectionPoolManager {

String databaseUrl = "jdbc:mysql://localhost:3306/homeland";
String userName = "root";
String password = "root";

Vector connectionPool = new Vector();

public ConnectionPoolManager() {
    initialize();
}

public ConnectionPoolManager(
// String databaseName,
        String databaseUrl, String userName, String password) {
    this.databaseUrl = databaseUrl;
    this.userName = userName;
    this.password = password;
    initialize();
}

private void initialize() {
    // Here we can initialize all the information that we need
    initializeConnectionPool();
}

private void initializeConnectionPool() {
    while (!checkIfConnectionPoolIsFull()) {
        System.out
                .println("Connection Pool is NOT full. Proceeding with adding new connections");
        // Adding new connection instance until the pool is full
        connectionPool.addElement(createNewConnectionForPool());
    }
    System.out.println("Connection Pool is full.");
}

private synchronized boolean checkIfConnectionPoolIsFull() {
    final int MAX_POOL_SIZE = 5;

    // Check if the pool size
    if (connectionPool.size() < 5) {
        return false;
    }

    return true;
}

// Creating a connection
private Connection createNewConnectionForPool() {
    Connection connection = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = (Connection) DriverManager.getConnection(databaseUrl,
                userName, password);
        System.out.println("Connection: " + connection);
    } catch (SQLException sqle) {
        System.err.println("SQLException: " + sqle);
        return null;
    } catch (ClassNotFoundException cnfe) {
        System.err.println("ClassNotFoundException: " + cnfe);
        return null;
    }

    return connection;
}

public synchronized Connection getConnectionFromPool() {
    Connection connection = null;

    // Check if there is a connection available. There are times when all
    // the connections in the pool may be used up
    if (connectionPool.size() > 0) {
        connection = (Connection) connectionPool.firstElement();
        connectionPool.removeElementAt(0);
    }
    // Giving away the connection from the connection pool
    return connection;
}

public synchronized void returnConnectionToPool(Connection connection) {
    // Adding the connection from the client back to the connection pool
    connectionPool.addElement(connection);
}

public static void main(String args[]) {
    new  ConnectionPoolManager();
}

}

can any one help? 有人可以帮忙吗?

The purpose of connection pooling is to maintain a number of open connections to a database so that when your application requires a connection it does not have to go through the potentially resource and time intensive process of opening a new connection. 连接池的目的是维护与数据库的许多打开的连接,以便当您的应用程序需要连接时,它不必经历可能耗费资源和时间的打开新连接的过程。

When an application requires a database connection it 'borrows' one from the pool. 当应用程序需要数据库连接时,它将从池中“借用”一个。 When it's done, it gives it back and that connection may be reused at some later point. 完成后,它会退还给您,以后可以重新使用该连接。

Once you have obtained a connection, you use it in your application through the JDBC (Java Database Connectivity) API. 一旦获得连接,就可以通过JDBC(Java数据库连接)API在应用程序中使用它。

Oracle's basic tutorial for using JDBC can be found at http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html 可以在http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html上找到Oracle使用JDBC的基本教程。

Another thing to keep in mind is that alot of work has gone into developing connection pools already, and it probably is not necessary to reinvent the wheel, except perhaps as a learning excercise. 要记住的另一件事是,很多工作已经投入到开发连接池中,并且可能不需要重新发明轮子,除非可能是作为学习练习。 Apache Tomcat's connection pool implementation can be used outside of Tomcat (for example, in a standalone Java application) and is fairly flexible and easy to configure. Apache Tomcat的连接池实现可以在Tomcat之外使用(例如,在独立的Java应用程序中),并且相当灵活且易于配置。 It can be found at https://people.apache.org/~fhanik/jdbc-pool/jdbc-pool.html 可以在https://people.apache.org/~fhanik/jdbc-pool/jdbc-pool.html中找到

I would say the code is pretty self explanatory. 我会说代码很容易解释。

You create an instance of the pool, personally, I prefer to use a singleton, but that's another topic 您个人创建了一个池实例,我更喜欢使用单例,但这是另一个主题

ConnectionPoolManager connectionPoolManager = new  ConnectionPoolManager();

Now, every body that wants a connection, is going to need a reference to this manager. 现在,每个想要建立连接的机构都需要向该管理器提供参考。 When you need to, you request a free connection from the pool... 必要时,您可以请求池中的免费连接...

public void queryDatabaseForStuff(ConnectionPoolManager cpm) throws SQLException {
    Connection con = cpm.getConnectionFromPool();
    //....

Once you're finished with the connection, you pass it back to the manager... 连接完成后,将其传递回经理...

 try {
     //...
 } finally {
     cmp.returnConnectionToPool(con);
 }

Now. 现在。 You might like to investigating a blocking process that will block the current call to getConnectionFromPool while the pool is empty, meaning that it will either throw an exception (if you want to include a time out feature) or a valid connection. 您可能想研究一个阻止过程,该过程将在池为空时阻止当前对getConnectionFromPool调用,这意味着它将抛出异常(如果要包含超时功能)或有效连接。

When re-pooling a Connection , you might like to check to see if the Connection has been closed or not and have some kind of revival process to ensure that the pool is awlays close to capcaity... 重新池化Connection ,您可能想检查Connection是否已关闭,并进行某种复兴,以确保池的容量接近容量...

Please check this link for getting detailed answer - https://examples.javacodegeeks.com/core-java/sql/jdbc-connection-pool-example/ 请查看此链接以获取详细的答案-https: //examples.javacodegeeks.com/core-java/sql/jdbc-connection-pool-example/

You don't need to recreate your Connection object pool , instead please use the libraries provided by Apache . 您无需重新创建Connection对象池,而请使用Apache提供的库。 Please be clear of the following : 1 - Why and what made you think of connection pool ? 请清除以下内容:1-为什么以及为什么让您想到连接池? 2 - Use the following Apache commons-dbcp lib in your Maven project and then use the classes as per documentation . 2-在您的Maven项目中使用以下Apache commons-dbcp lib,然后根据文档使用这些类。 3. Does this solve all your problems ? 3.这样可以解决您所有的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM