푸린세스

커넥션 풀 설정 본문

spring/구멍가게코딩단-스프링

커넥션 풀 설정

푸곰주 2023. 5. 1. 12:53

 

여러명의 사용자를 동시에 처리할 경우

- DB연결시에 커넥션풀을 이용한다.

 

스프링에 커넥션풀을 등록해서 사용하자.

 

Java에서는 DataSource라는 인터페이스를 통해서 커넥션풀을 사용한다.

즉 DataSource를 통해 매번 DB와 연결하는 방식이 아닌

미리 연결을 맺어주고 반환하는 구조를 이용하여 성능향상을 꾀한다. + 안정성면에서도 더 좋다.

 

커넥션풀에는 여러 종류있음

-spring-jdbc 라이브러리 이용하는방식

-HikariCP 이용하는방식

 

1.라이브러리를 추가한다. (pom.xml에 수정)

<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>2.7.4</version>
</dependency>

 

 

2.root-context.xml 수정한다.   (Java설정을 이용하는 경우 RootConfig클래스에서 수정하면 된다.)

<?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 https://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 -->
	
	<context:component-scan base-package="org.moominzero.sample"></context:component-scan>
	<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
	<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
	
	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ex?autoReconnect=true&amp;useSSL=false&amp;serverTimezone=UTC"></property>
	<property name="username" value="root"></property>
	<property name="password" value="1111"></property></bean> 
	
	
<bean class="com.zaxxer.hikari.HikariDataSource" id="dataSource" destroy-method="close">

<constructor-arg ref="hikariConfig"/>

</bean>

<context:component-scan base-package="org.moominzero.sample"> </context:component-scan>


	
		
</beans>

 

스프링 시작되면 root-context.xml을 읽어서

id가 dataSource인 객체가 처리된다.

 

 

3. 테스트 작성하기 : DataSourceTests클래스 작성

-빈으로 등록된 DataSource를 이용해서 Connection을 제대로 처리할 수 있는지 확인해보기

package org.moominzero.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.moominzero.sample.SampleTests;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import lombok.extern.log4j.Log4j;

@RunWith(SpringJUnit4ClassRunner.class) //테스트시 필요한 클래스 지정 (스프링은 SpringJunit4ClassRunner클래스가 대상이된다.)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml") //어떤 설정정보를 읽어들어야하는지.
@Log4j
public class DataSourceTests {

	@Autowired
	private DataSource ds;

	
	@Test
	public void testConnection()  {
		try(Connection con = ds.getConnection()){
			log.info(con);
		}catch(Exception e) {
			e.printStackTrace();
			
		}
	}

}

 

testConnection()의 실행결과: 내부적으로 HikariCp가 시작되고, 종료되는 로그를 확인하였다.

INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@22fcf7ab, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@2de23121, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@63475ace, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4988d8b8]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:src/main/webapp/WEB-INF/spring/root-context.xml]
INFO : org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext@7e9131d5: startup date [Mon May 01 12:53:59 KST 2023]; 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...
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
INFO : org.moominzero.persistence.DataSourceTests - HikariProxyConnection@641030345 wrapping com.mysql.cj.jdbc.ConnectionImpl@1f14f20c
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@7e9131d5: startup date [Mon May 01 12:53:59 KST 2023]; root of context hierarchy
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.

 

 


vs JDBCtest (Java와 JDBC드라이버만으로 테스트수행)

 

package org.moominzero.persistence;

import static org.junit.Assert.fail;

import java.sql.Connection;
import java.sql.DriverManager;

import org.junit.Test;

import lombok.extern.log4j.Log4j;

@Log4j
public class JDBCTests {
	static {

		try {
		Class.forName("com.mysql.cj.jdbc.Driver");
		}catch (Exception e) {
		e.printStackTrace();
		}
	}


		@Test
		public void testConnection() {
        
		try(Connection con = DriverManager.getConnection(
		"jdbc:mysql://localhost:3306/ex?autoReconnect=true&useSSL=false&serverTimezone=UTC",
		"root","1111")){
		log.info(con);      
		} catch (Exception e) {
		e.printStackTrace();
		}
	}
}

실행결과:  정상적으로 DB가 연결된 connection객체가 출력되었다.

INFO : org.moominzero.persistence.JDBCTests - com.mysql.cj.jdbc.ConnectionImpl@26e356f0

 

만번을 연결을 맺었다 끊었다 하는 경우에 속도나 안정성 면에서 커넥션풀을 이용하는 경우가 더 우수하므로

커넥션 풀을 사용하자.

 

'spring > 구멍가게코딩단-스프링' 카테고리의 다른 글

p190 MySQL~Oracle  (0) 2023.05.03
스프링MVC의 기본사상  (0) 2023.05.02
스프링MVC 기본구조  (0) 2023.05.02
MyBatis ~ 스프링과 연동처리  (0) 2023.05.01
구멍가게코딩단-스프링 p56  (0) 2023.05.01