본문 바로가기

Spring

Spring 커넥션 풀


c3p0의 ComboPooledDataSource사용

 

pom.xml 설정 추가


	<dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>12.1.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5</version>
        </dependency>

 

스프링 설정파일로 구현


        <beans:bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	    <beans:property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
	    <beans:property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcle" />
	    <beans:property name="user" value="c##scott" />
	    <beans:property name="password" value="tiger" />
	    <beans:property name="maxPoolSize" value="200" />
	    <beans:property name="checkoutTimeout" value="60000" />
	    <beans:property name="maxIdleTime" value="1800" /> 
	    <beans:property name="idleConnectionTestPeriod" value="600" />
	</beans:bean>

자바파일로 어노테이션 사용


@Configuration
public class DBConfig {
	
	@Bean
	public ComboPooledDataSource dataSource() throws PropertyVetoException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		
		dataSource.setDriverClass("oracle.jdbc.driver.OracleDriver");
		dataSource.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:orcle");
		dataSource.setUser("c##scott");
		dataSource.setPassword("tiger");
		dataSource.setMaxPoolSize(200);
		dataSource.setCheckoutTimeout(60000);
		dataSource.setMaxIdleTime(1800);
		dataSource.setIdleConnectionTestPeriod(600);
		
		return dataSource;
	}
}

 

Dao 파일에서 dataSource 가져와서 사용


	@Autowired
	private DataSource dataSource;
    
	@Override
	public int memberInsert(final Member member) {
	    Connection conn = null;
	    PreparedStatement pstmt = null; 
	    String sql = "insert into member values(?, ?, ?)";
	    
	    try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, member.getMemId());
			pstmt.setString(2, member.getMemPw());
			pstmt.setString(3, member.getMemMail());
			
			return pstmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        return -1;
        }