데이터베이스 커넥션이란 동일한 시스템에 있든 없든 데이터베이스 서버가 소프트웨어와 통신할 수 있도록 하는 컴퓨터 과학의 기능이다. 커넥션은 명령을 전달하고 대답을 수신할 수 있어야 한다. 출처: https://en.wikipedia.org/wiki/Database_connection
Connection
객체가 제공된다.
DirverMangaer.getConnection
으로 Connection
을 생성할 수 있다.
Connection
을 연결 및 생성하는 것은 비싼 작업이므로 요청마다 Connection
을 새로 만든다면 성능 이슈가 발생할 수도 있다.
커넥션 풀은 잘 알려진 데이터 엑세스 패턴으로 데이터베이스 커넥션 성능 오버헤드를 줄이기 위한 목적으로 사용된다.
Datasource
DataSource
객체를 사용해 데이터베이스 커넥션을 관리한다.DataSource
를 사용해 애플리케이션 코드에서 커넥션 풀과 트랜잭션 관련 코드를 숨길 수 있다.Supported Connection Pools
Spring Boot uses the following algorithm for choosing a specific implementation:
- We prefer HikariCP for its performance and concurrency. If HikariCP is available, we always choose it.
- Otherwise, if the Tomcat pooling
DataSource
is available, we use it.- Otherwise, if Commons DBCP2 is available, we use it.
- If none of HikariCP, Tomcat, and DBCP2 are available and if Oracle UCP is available, we use it
spring-boot-starter-jdbc
나spring-boot-starter-data-jpa
“starters” 의존성을 추가하면 자동으로HikariCP
의존성이 추가된다.
HikariCP는 Brett Wooldridge가 개발한 매우 가볍고 빠른 JDBC 커넥션 풀 프레임워크다.
HikariCP는 내부에서 ConcurrentBag
이라는 구조체로 Connection
을 관리하는데 HikariPool.getConnection()
→ ConcurrentBag.borrow()
라는 메서드로 유휴 Connection을 리턴한다.
default maximumPoolSize = 10
HikariCP 동작 원리
EntityManagerFactory
를 하나만 생성한다.EntityManager
를 생성한다. (EntityManager
를 생성하는 비용은 거의 안 든다)EntityManager
는 바로 Connection을 Connection Pool에서 꺼내오지 않고 필요한 시점 (트랜잭션 시작)에 Connection을 획득한다.동시 사용자 요청 수에 따라 다르지만 일반적인 공식이 있긴 있다.
Pool Size = Tn x (Cm - 1) + 1
Pool Size = Tn x (Cm - 1) + (Tn / 2)
(우아한 형제들 기술 블로그 참고)https://www.baeldung.com/java-connection-pooling