4 분 소요

 인프런 스프링 DB 1편 - 데이터 접근 핵심 원리편을 학습하고 정리한 내용 입니다.

DataSource 예제2 - 커넥션 풀

DataSource 를 통해 커넥션 풀을 사용하는 예제를 알아보자.

ConnectionTest - 데이터소스 커넥션 풀 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test  
void dataSourceConnectionPool() throws SQLException, InterruptedException {  
    //커넥션 풀링  
    HikariDataSource dataSource = new HikariDataSource();  
    dataSource.setJdbcUrl(URL);  
    dataSource.setUsername(USERNAME);  
    dataSource.setPassword(PASSWORD);  
    dataSource.setMaximumPoolSize(10); // default  
    dataSource.setPoolName("MyPool");  
  
    useDataSource(dataSource);  
    Thread.sleep(1000);  
}
  • HikariCP커넥션 풀을 사용한다. HikariDataSourceDataSource인터페이스를 구현하고 있다.
  • 커넥션 풀 최대 사이즈를 10으로 지정하고, 풀의 이름을 MyPool이라 지정했다.
  • 커넥션 풀에서 커넥션을 생성하는 작업은 애플리케이션 실행 속도에 영향을 주지 않기 위해 별도의 드서 작동한다. 별도의 쓰레드에서 동작하기 때문에 테스트가 먼저 종료되어 버린다. 예제처럼 Thread.sleep을 통해 대기 시간을 주어야 쓰레드 풀에 커넥션이 생성되는 로그를 확인할 수 있다.

스프링 부트 3.1 이상 - 로그 출력 안되는 문제 해결

히카리 커넥션 풀을 테스트하는 dataSourceConnectionPool()을 실행할 때, 스프링 부트 3.1 이상을 사용한다면 전체 로그가 아니라 간략한 로그만 출력 된다.

이때는 다음 위치에 파일을 만들어서 넣으면 된다.

src/main/resources/logback.xml

1
2
3
4
5
6
7
8
9
10
11
<configuration>  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">  
        <encoder>  
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%kvp-  
                %msg%n</pattern>  
        </encoder>  
    </appender>  
    <root level="DEBUG">  
        <appender-ref ref="STDOUT" />  
    </root>  
</configuration>

스프링 부트 3.1 부터 기본 로그 레벨을 INFO로 빠르게 설정하기 때문에 로그를 확인할 수 없는데, 이렇게하면 기본 로그 레벨을 DEBUG로 설정해서 강의 내용과 같이 로그를 확인할 수 있다.

ConnectionTest - 데이터소스 커넥션 풀 결과

HikariConfig

HikariCP관련 설정을 확인할 수 있다. 풀의 이름(MyPool)과 최대 풀 수(10)을 확인할 수 있다.

MyPool connection adder

별도의 쓰레드 사용해서 커넥션 풀에 커넥션을 채우고 있는 것을 확인할 수 있다. 이 쓰레드는 커넥션 풀에 커넥션을 최대 풀 수(10)까지 채운다

그렇다면 왜 별도의 쓰레드를 사용해서 커넥션 풀에 커넥션을 채우는 것일까?

커넥션 풀에 커넥션을 채우는 것은 상대적으로 오래 걸리는 일이다. 애플리케이션을 실행할 때 커넥션 풀을 채울 때 까지 마냥 대기하고 있다면 애플리케이션 실행 시간이 늦어진다. 따라서 이렇게 별도의 쓰레드를 사용해서 커넥션 풀을 채워야 애플리케이션 실행 시간에 영향을 주지 않는다.

커넥션 풀에서 커넥션 획득

커넥션 풀에서 커넥션을 획득하고 그 결과를 출력했다. 여기서는 커넥션 풀에서 커넥션을 2개 획득하고 반환하지는 않았다. 따라서 풀에 있는 10개의 커넥션 중에 2개를 가지고 있는 상태이다. 그래서 마지막 로그를 보면 사용중인 커넥션 active=2, 풀에서 대기 상태인 커넥션 idle=8을 확인할 수 있다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void useDataSource(DataSource dataSource) throws SQLException {  
    Connection con1 = dataSource.getConnection();  
    Connection con2 = dataSource.getConnection();  
    Connection con3 = dataSource.getConnection();  
    Connection con4 = dataSource.getConnection();  
    Connection con5 = dataSource.getConnection();  
    Connection con6 = dataSource.getConnection();  
    Connection con7 = dataSource.getConnection();  
    Connection con8 = dataSource.getConnection();  
    Connection con9 = dataSource.getConnection();  
    Connection con10 = dataSource.getConnection();  
    Connection con11 = dataSource.getConnection();  
    log.info("connection={}, class={}", con1, con1.getClass());  
    log.info("connection={}, class={}", con2, con2.getClass());  
}

만약 10개인데 11개 맺으면 어떻게 될까?

10개인데 더 원해서 추가되지 못한다고 계속 대기중이다.

그러다 기본 세팅인 30초가 지나면

다음과 같이 에러가 발생한다.

DataSource 적용

이번에는 애플리케이션에 DataSource를 적용해보자.

기존 코드를 유지하기 위해 기존 코드를 복사해서 새로 만들자.

  • MemberRepositoryV0 → MemberRepositoryV1
  • MemberRepositoryV0Test → MemberRepositoryV1Test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**  
 * JDBC - dataSource 사용, JdbcUtils 사용  
 * */  
@Slf4j  
public class MemberRepositoryV1 {  
  
    private final DataSource dataSource;  
  
    public MemberRepositoryV1(final DataSource dataSource) {  
        this.dataSource = dataSource;  
    }  
  
    public Member save(Member member) throws SQLException {  
        String sql = "insert into member(member_id, money) values (?, ?)";  
	    ..
        ..
    }  
  
    public Member findById(String memberId) throws Exception {  
        String sql = "select * from member where member_id = ?";  
		..
    }  
  
    public void update(String memberId, int money) throws Exception {  
        String sql = "update member set money = ? where member_id = ?";  
		...
    }  
  
    public void delete(String memberId) throws Exception {  
        String sql = "delete from member where member_id = ?";  
       ..
    }  
  
    private void close(Connection conn, Statement stmt, ResultSet rs) {  
        JdbcUtils.closeResultSet(rs);  
        JdbcUtils.closeStatement(stmt);  
        JdbcUtils.closeConnection(conn);  
    }  
  
    private Connection getConnection() throws SQLException {  
        Connection connection = dataSource.getConnection();  
        log.info("get connection= {}", connection);  
        return connection;  
    }  
}

실제 crud코드는 v0와 동일하다. 바뀐건 getConnection, close다.

  • DataSource 의존관계 주입
    • 외부에서 DataSource를 주입 받아서 사용한다. 이제 직접 만든 DBConnectionUtil을 사용하지 않아도 된다.
    • DataSource는 표준 인터페이스 이기 때문에 DriverManagerDataSource에서 HikariDataSource로 변경되어도 해당 코드를 변경하지 않아도 된다.
  • JdbcUtils 편의 메서드
    • 스프링은 JDBC를 편리하게 다룰 수 있는 JdbcUtils라는 편의 메서드를 제공한다.
    • JdbcUtils을 사용하면 커넥션을 좀 더 편리하게 닫을 수 있다.

MemberRepositoryV1Test

이제 테스트 해보자.

먼저 DriverManagerDataSourcedataSource를 획득하면 어떤 일이 벌어지는지 보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Slf4j  
class MemberRepositoryV1Test {  
  
    MemberRepositoryV1 repository;  
  
    @BeforeEach  
    void beforeEach() {  
        // 기본 DriverManager - 항상 새로운 커넥션을 획득  
        DriverManagerDataSource dataSource = new DriverManagerDataSource(URL, USERNAME, PASSWORD);  
        repository = new MemberRepositoryV1(dataSource);  
    }  
  
    @Test  
    void crud() throws Exception {  
        //save  
        Member member = new Member("memberTest", 10000);  
        repository.save(member);  
  
        //findById  
        Member findMember = repository.findById(member.getMemberId());  
        log.info("findMember = {}", findMember);  
  
        assertThat(findMember).isEqualTo(member);  
  
        //update: money : 10000 -> 20000  
        repository.update(member.getMemberId(), 20000);  
        Member updatedMember = repository.findById(member.getMemberId());  
        assertThat(updatedMember.getMoney()).isEqualTo(20000);  
  
        //delete  
        repository.delete(member.getMemberId());  
        assertThatThrownBy(() -> repository.findById(member.getMemberId()))  
                .isInstanceOf(NoSuchElementException.class);  
  
    }  
}

DriverManagerDataSource를 사용하면 conn0~5번호를 통해서 항상 새로운 커넥션이 생성되어서 사용 되는 것을 확인할 수 있다.

그럼 이제 HikariDataSource를 사용해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
@BeforeEach  
void beforeEach() {  
    // 기본 DriverManager - 항상 새로운 커넥션을 획득  
    //DriverManagerDataSource dataSource = new DriverManagerDataSource(URL, USERNAME, PASSWORD);  
  
    //커넥션 풀링  
    HikariDataSource dataSource = new HikariDataSource();  
    dataSource.setJdbcUrl(URL);  
    dataSource.setUsername(USERNAME);  
    dataSource.setPassword(PASSWORD);  
  
    repository = new MemberRepositoryV1(dataSource);  
}

  • 커넥션 풀 사용 시 conn0 커넥션이 재사용 된 것을 확인할 수 있다.
  • 테스트는 순서대로 실행되기 때문에 커넥션을 사용하고 다시 돌려주는 것을 반복한다. 따라서 conn0만 사용된다.
  • 웹 애플리케이션에 동시에 여러 요청이 들어오면 여러 쓰레드에서 커넥션 풀의 커넥션을 다양하게 가져가는 상황을 확인할 수 있다.

DI

DriverManagerDataSourceHikariDataSource로 변경해도 MemberRepositoryV1의 코드는 전혀 변경하지 않아도 된다. MemberRepositoryV1DataSource 인터페이스에만 의존하기 때문이다.

이것이 DataSource를 사용하는 장점이다.(DI + OCP)

댓글남기기