본문으로 바로가기

▶커넥션풀 설정

여러 명의 사용자를 동시에 처리해야한는 웹 에플리케이션의 경우 데이터베이스 연결을 이용할 때는 '커넥션풀을(connection Pool)' 이용하므로 스프링에 커넥션풀을 등록해서 사용하는 것이 좋음.

자바에서는 DataSource라는 인터페이스를 통해서 커넥션 풀을 사용함.DataSource를 통해 매번 데이터베이스와 연결하는 방식이 아닌,미리 연결을 맺어주고 반환하는구조를 이용하여 성능 향상을 꾀함. 


커넥션 풀은 여러종류가 있고 spring-jdbc 라이브러리를 이용할 수도 있지만 최근 유행하는 HikariCP(https://github.com/brettwooldridge/HikariCP)를 이용해 보겠음.HikariCP는 스프링 부트2.0에서도 사용될 만큼빠르게 퍼지고 있음. 


-라이브러리 추가와 DateSource설정

pom.xml을 수정해서 HikariCP 를 추가 

1
2
3
4
5
6
<!-- HikariCP -->
         <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>3.1.0</version>
        </dependency>
cs

root-context.xml 안에 설정은 직접<bean> 태그를 정의해서 작성합니다.<bean>태그 내에는 <property>를 이용해서 여러 속성에 대해서 설정할 수 있는데 HikariCP에 대한 자세한 설정은 https://github.com/brettwooldridge/HikariCP#configuration-knobs-baby 여기 참고.
예제는 최솨한의 설정만을 이용해서 작성.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
        
        <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
        <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
        <property name="username" value="TEST_EX"></property>
        <property name="password" value="1234"></property>
        </bean>
        
        <!--HikariCP Configration-->
        <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
        <constructor-arg ref="hikariConfig"/>
        </bean>
        
        <context:component-scan base-package="org.zeorck.sample"></context:component-scan>
</beans>
 
cs


-root-context.xml은 스프링이 로딩되면서 읽어 들이는 문서이므로 ,주로 이미 만들어진 클래스들을 이용해서 스프링 빈(Bean)으로 등록할 때 사용됨.

일반적인 상황이라면 프로젝트에 직접작성하는 클래스들은 어노테이션을 이용하는 경우가 많고 ,외부 jar파일 등으로 사용하는 클래스들은 <bean>태그를 이용해서작성하는 경우가 대부분입니다.


JAVA설정을 이용하는 경우



RootConfig클래스와 @Bean을 이용해서 처리함.

@Bean은 XML설정에서 <bean>태그와 동일한 역할을 한다고 생각하면됨.@Bean이 선언된 메서드의 실행 결과로 반환된 객체는 스프링의 객체(@Bean)로 등록됨.


RootConfig 클래스 

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
package org.zerock.config;
 
import javax.sql.DataSource;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
 
 
@Configuration
@ComponentScan(basePackages= {"org.zerock.sample"})
public class RootConfig {
    
    
    @Bean
    public DataSource dataSource() {
         HikariConfig hikariConfig =new HikariConfig();
         hikariConfig.setDriverClassName("jdbc:oracle:thin@local");
         hikariConfig.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:orcl");
         hikariConfig.setUsername( "TEST_EX");
         hikariConfig.setPassword("1234");
         
         HikariDataSource dataSource=new HikariDataSource(hikariConfig);
         return dataSource;
    }
 
}
 
cs




스프링이 시작되면 root-context.xml을 읽어서 아래와 같은 형태로 id가 datasource인 객체가 처리됨.

경험이 적으신 분들은 위와 같이 빈(Bean)을 정의한 다음에 항상 테스트를 작성한는 습관을 가지는 것이 좋음. (이전 JDBC코드를 테스트는 동일하니 갖다 쓰시면 됩니다.)


(지금 부터는 Java방식과 XML방식 두가지 다 알아보겠음.)

(진짜 이거 할 때 오타......주의 하세요..... ㅜㅜㅜ  진짜 ... 잘못하다 꼬이면  머리 다빠짐.)

DataSourceTest클래스를 만드고 아래 코드를 추가함.





DataSourceTest

여기 JAVA와 XML 방식이 있으니 저것만 바꿔서 사용화면된다 

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
package org.zeorck.persistence;
 
import static org.junit.Assert.fail;
 
import java.sql.Connection;
 
import javax.sql.DataSource;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.zeorck.config.RootConfig;
 
import lombok.Setter;
import lombok.extern.log4j.Log4j;
 
@RunWith(SpringJUnit4ClassRunner.class)
//xml설정을 이용하는 경우
/*@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")*/
//JAVA설정을 사용하는 경우
@ContextConfiguration(classes= {RootConfig.class})
@Log4j
public class DataSourceTest {
 
    @Setter(onMethod_ = {@Autowired})
    private DataSource dataSource;
    
    @Test
    public void testConnection() {
        try (Connection con= dataSource.getConnection()){
            
            log.info(con);
            
        } catch (Exception e) {
            fail(e.getMessage());
            
        }
    }
    
}
 
cs


테스트 코드는 스프링 빈으로 등록 된 DataSuorce를 이용해서 Connection을 제대로 처리할 수있는지 확인해 보는 용도.

이렇게 완료가 되었으면 testConnection()을  Junit으로 실행.

실행 결과 

내부적으로 HikariCP가 시작 되고 ,종료되는 로그를 확인할 수 있다 

1
2
3
4
5
6
7
8
9
10
11
12
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@523884b2, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@5b275dab, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@61832929, org.springframework.test.context.support.DirtiesContextTestExecutionListener@29774679]
INFO : org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext@7e0b0338: startup date [Fri Dec 14 11:40:20 KST 2018]; root of context hierarchy
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
WARN : com.zaxxer.hikari.util.DriverDataSource - Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
INFO : org.zeorck.persistence.DataSourceTest - HikariProxyConnection@1443055846 wrapping oracle.jdbc.driver.T4CConnection@2e222612
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@7e0b0338: startup date [Fri Dec 14 11:40:20 KST 2018]; root of context hierarchy
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.
 
cs