programing

JDBC Connection Pooling을 사용하고 있습니까?

lovejava 2023. 10. 16. 21:26

JDBC Connection Pooling을 사용하고 있습니까?

제가 실제로 JDBC 연결 풀링을 사용하고 있는지 확인하려고 합니다.몇 가지 조사를 해보니 실행이 너무 쉬워 보입니다.사실 일반적인 접속보다 쉬워서 확인하고 싶습니다.

내 연결 클래스는 다음과 같습니다.

public class DatabaseConnection {

Connection conn = null;

public Connection getConnection() {

    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl("jdbc:mysql://localhost:3306/data");
    bds.setUsername("USERNAME");
    bds.setPassword("PASSWORD");

    try{
        System.out.println("Attempting Database Connection");
        conn = bds.getConnection();
        System.out.println("Connected Successfully");
    }catch(SQLException e){
        System.out.println("Caught SQL Exception: " + e);
    }
    return conn;
}

public void closeConnection() throws SQLException {
    conn.close();
}

}

이것이 진정한 연결 풀링입니까?다른 클래스의 연결을 다음과 같이 사용합니다.

        //Check data against database.
    DatabaseConnection dbConn = new DatabaseConnection();
    Connection conn;
    ResultSet rs;
    PreparedStatement prepStmt;

    //Query database and check username/pass against table.
    try{
        conn = dbConn.getConnection();
        String sql = "SELECT * FROM users WHERE username=? AND password=?";
        prepStmt = conn.prepareStatement(sql);
        prepStmt.setString(1, user.getUsername());
        prepStmt.setString(2, user.getPassword());
        rs = prepStmt.executeQuery();

        if(rs.next()){ //Found Match.
            do{
                out.println("UserName = " + rs.getObject("username") + " Password = " + rs.getObject("password"));
                out.println("<br>");
            } while(rs.next());
        } else {
            out.println("Sorry, you are not in my database."); //No Match.
        }

        dbConn.closeConnection(); //Close db connection.

    }catch(SQLException e){
        System.out.println("Caught SQL Exception: " + e);
    }

DBCP에서 가져온 것이라고 가정하면 예, 연결 풀을 사용하는 것입니다.그러나 모든 연결 획득 시 다른 연결 풀을 다시 생성하는 것입니다.같은 풀에서 연결을 풀링하는 것이 아닙니다.응용 프로그램을 시작할 때 연결 풀을 한 번만 만들고 모든 연결을 가져와야 합니다.또한 연결을 인스턴스(instance) 변수로 고정해서는 안 됩니다.또한 예외의 경우에도 리소스가 제대로 닫히도록 연결, 문 및 결과 집합을 닫아야 합니다.자바 7의 문장은 이것에 도움이 되며, 이것은 리소스를 자동으로 닫을 것입니다.try블록이 끝났습니다.

다음은 약간의 재작성입니다.

public final class Database {

    private static final BasicDataSource dataSource = new BasicDataSource();

    static {
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/data");
        dataSource.setUsername("USERNAME");
        dataSource.setPassword("PASSWORD");
    }

    private Database() {
        //
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

}

(필요한 경우 플러그인성을 개선하기 위해 추상적 공장으로 재분류될 수 있음)

그리고.

private static final String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";

public boolean exist(User user) throws SQLException {
    boolean exist = false;

    try (
        Connection connection = Database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_EXIST);
    ) {
        statement.setString(1, user.getUsername());
        statement.setString(2, user.getPassword());

        try (ResultSet resultSet = preparedStatement.executeQuery()) {
            exist = resultSet.next();
        }
    }       

    return exist;
}

다음과 같이 사용합니다.

try {
    if (!userDAO.exist(username, password)) {
        request.setAttribute("message", "Unknown login. Try again.");
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    } else {
        request.getSession().setAttribute("user", username);
        response.sendRedirect("userhome");
    }
} catch (SQLException e) {
    throw new ServletException("DB error", e);
}

그러나 실제 Java EE 환경에서는 다음의 생성을 위임해야 합니다.DataSource컨테이너/응용프로그램 서버로 전송하고 JNDI에서 이를 가져옵니다.Tomcat의 경우, 이 문서의 예도 참조하십시오. http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html

풀링된 것 같지는 않네요각 getConnection() 호출을 사용하여 새 데이터 소스를 생성하는 대신 DatabaseConnection에 데이터 소스를 저장해야 합니다.getConnection()은 datasource.getConnection()을 반환해야 합니다.

DBCP 사용으로 보입니다.만약 그렇다면, 네.이미 풀링 됐어요.다음은 DBCP의 기본 풀 속성 값입니다.

/**
* The default cap on the number of "sleeping" instances in the pool.
* @see #getMaxIdle
* @see #setMaxIdle
*/
public static final int DEFAULT_MAX_IDLE  = 8;
/**
* The default minimum number of "sleeping" instances in the pool
* before before the evictor thread (if active) spawns new objects.
* @see #getMinIdle
* @see #setMinIdle
*/
public static final int DEFAULT_MIN_IDLE = 0;
/**
* The default cap on the total number of active instances from the pool.
* @see #getMaxActive
*/
public static final int DEFAULT_MAX_ACTIVE  = 8;

BalusC 솔루션의 후속으로 아래는 둘 이상의 연결이 필요한 애플리케이션이나 연결 속성을 미리 알 수 없는 공통 라이브러리에서 사용할 수 있는 구현입니다.

import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;

public final class Database {

    private static final ConcurrentHashMap<String, BasicDataSource> dataSources = new ConcurrentHashMap();

    private Database() {
        //
    }

    public static Connection getConnection(String connectionString, String username, String password) throws SQLException {

        BasicDataSource dataSource;

        if (dataSources.containsKey(connectionString)) {
            dataSource = dataSources.get(connectionString);
        } else {
            dataSource = new BasicDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl(connectionString);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            dataSources.put(connectionString, dataSource);
        }

        return dataSource.getConnection();

    }

}

언급URL : https://stackoverflow.com/questions/7592056/am-i-using-jdbc-connection-pooling