의존성
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
커넥션 풀 설정 : DBCPinit
package jdbc;
import org.apache.commons.dbcp2.*;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBCPInit extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("잘되니?");
loadJDBCDriver();
initConnectionPool();
}
private void loadJDBCDriver() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("fail to load jdbc Driver",e);
}
}
private void initConnectionPool() {
String url = "jdbc:mysql://localhost:3306/guestbook?characterEncoding=UTF-8&useSSL=false";
String uid = "root";
String upw = "1234";
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url,uid,upw);
PoolableConnectionFactory poolableConnectionFactory =
new PoolableConnectionFactory(connectionFactory,null);
poolableConnectionFactory.setValidationQuery("select 1");
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setTestWhileIdle(true);
poolConfig.setMinIdle(4);
poolConfig.setMaxTotal(50);
GenericObjectPool<PoolableConnection> connectionPool =
new GenericObjectPool<>(poolableConnectionFactory,poolConfig);
try {
Class.forName("org.apache.commons.dbcp2.PoolingDriver");
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
driver.registerPool("guestbook",connectionPool);
} catch (ClassNotFoundException | SQLException e) {
throw new RuntimeException(e);
}
}
}
web.xml
<servlet>
<servlet-name>dbcpInit</servlet-name>
<servlet-class>jdbc.DBCPInit</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
커넥션풀 사용 : ConnectionProvider
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionProvider {
public static Connection getConnection() throws SQLException {
String url = "jdbc:apache:commons:dbcp:guestbook";
return DriverManager.getConnection(url);
}
}
컨트롤러 서블릿 패턴 (0) | 2020.07.05 |
---|---|
커넥션 풀 connection pool : 초기화파라미터 지정 (0) | 2020.07.05 |
서블릿 구현, 애노테이션 맵핑 (0) | 2020.07.05 |
[Mac, IntelliJ, tomcat] 맥 인텔리제이에서 톰캣 연동 (0) | 2020.06.19 |
[Mac, elipse, tomcat] 이클립스에서 톰캣 연동 (0) | 2020.06.19 |
댓글 영역