728x90
300x250

[Spring-Framework] 40. Connection Pool - xml 정리(Oracle, MySQL, HikariCP, Apache DBCP)


root-context.xml과 같은 context.xml 파일에 빈스(Beans)로 등록해서 사용할 때 매우 요긴하게 사용될 수 있는 DataSource에 대해서 정리하였다.

의외로 정리된 자료를 찾기가 귀찮아서 정리하였으니 참고하여 잘 사용하면 된다.


연관 글은 38, 39번 Spring-Framework에도 적용해볼 수 있다.



1. 정리


많이 필요한 경우가 생긴다. 이거 찾는데 시간 허비하지 말라고 작성한다.


[추가]
     <!-- MySQL - DataSource 셋팅 -->
    <bean id="dataSource2" class="com.mysql.cj.jdbc.MysqlDataSource">
        <property name="URL" value="${ORACLE_DB_URL}" />
        <property name="user" value="${ORACLE_DB_USERNAME}"/>
        <property name="password" value="${ORACLE_DB_PASSWORD}"/>
    </bean>


    <!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
 
     <!-- 2. Oracle - DataSource 셋팅 -->
    <bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
        <property name="URL" value="${ORACLE_DB_URL}" />
        <property name="user" value="${ORACLE_DB_USERNAME}"/>
        <property name="password" value="${ORACLE_DB_PASSWORD}"/>
        <property name="connectionCachingEnabled" value="true"/>
    </bean>

    <!-- 3. Apache DBCP -->

   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
         <property name="driverClassName" value="${jdbc.driverClassName}" />
         <property name="url" value="${jdbc.url}" />
         <property name="username" value="${jdbc.username}" />
         <property name="password" value="${jdbc.password}" />
   </bean>


    <!-- 4. HikariCP -->
    <!--
    <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
         <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
         <property name="username" value="username" />
         <property name="password" value="password" />
    </bean>
 
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
          <constructor-arg ref="hikariConfig"/>
    </bean>
     -->



    <!-- 5. MariaDB -->
    <!--
    <bean id="dataSource4" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="org.mariadb.jdbc.Driver"/>
        <property name="url" value="jdbc:mariadb://localhost:3306/test"></property>
        <property name="username" value="root"/>
        <property name="password" value="test"/>
    </bean>
     -->
    
    <!-- 6. MyBatis // 트랜젝션 적용 버전 -->
    <!--
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource4"/>
        <property name="configLocation" value="classpath:mybatis/config.xml"/>
        <property name="mapperLocations" value="classpath:mybatis/sql/*.xml"></property>
    </bean>
   
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
   
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource4"/>
    </bean>
   
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
     -->





2. 공식 사이트


http://commons.apache.org/proper/commons-dbcp/

https://github.com/brettwooldridge/HikariCP

-> 메뉴얼이 다소 부족하다. 깔끔하게 잘 정리는 되어 있는데 그런 점이 없는 건 아니다. 


https://www.oracle.com/kr/

https://www.mysql.com/

https://mariadb.org/

반응형
728x90
300x250

[Spring-Framework] 10. Spring MVC - HikariCP 3.4.2, Oracle 19g 연동하기(Properties, Java) - (1)


Spring MVC 프로젝트로 HikariCP 3.4.2를 연동하는 방법에 대해서 소개하겠다.

Apache DBCP(커넥션 풀) 프로젝트도 있으나 최근에는 HikariCP가 성능이 더 우수하다고 한다.


양이 많은 주제이므로 2부로 나눠서 작성하였다.



1. Introduce(소개) - 커넥션 풀


1. 커넥션 풀(DBCP)이란?

웹 컨테이너(WAS)가 실행되면서 DB와 미리 connection(연결)을 해놓은 객체들을 pool에 저장해두었다가, 클라이언트 요청이 오면 connection을 빌려주고, 처리가 끝나면 다시 connection을 반납받아 pool에 저장하는 방식을 말한다.



2. 작업환경


이 글에서 사용한 작업 환경이다.


* IDE: Spring Tool-Suite 4-4.7.2 Releases(Eclipse)


* Web Server(웹서버):

Apache Tomcat 9


* 데이터베이스(Databases)

Oracle Databases 19

MySQL 8.0.21


* 프레임워크

Spring Framework 3.1.1 Releases


* 라이브러리

POM - Oracle JDBC 19

POM - MySQL 8.0.21

Maven Project - 3.6.3/1.16.0.20200610-1735


특징: MyBatis 제거 등 영속 프레임워크 미적용




3. 프로젝트 구성


작업할 프로젝트의 구성이다.



그림 1. 프로젝트 구성




4. 새 프로젝트 생성


File -> New -> Others...

                 Spring 폴더-> Spring Legacy Projects



5. pom.xml 설정





그림 2. POM.xml 수정 - 자바 버전 수정하기


[JAVA JDK 버전 오류]

오류 : Resource specification not allowed here for source level below 1.7


자바 버전을 변경하는 이유는 1.6으로는 버전이 낮아서 미지원한다고 오류가 발생하기 때문이다.

pom.xml 셋팅 후 project에서 변경을 해줘야 한다.


그림 3. POM.xml 수정 - Spring Test 영역 수정하기



그림 4. POM.xml 수정 - HikariCP, Oracle JDBC


      <properties>

<java-version>14</java-version>

<org.springframework-version>3.1.1.RELEASE</org.springframework-version>

<org.aspectj-version>1.6.10</org.aspectj-version>

<org.slf4j-version>1.6.6</org.slf4j-version>

</properties>


(중략)


<!-- spring-test -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-test</artifactId>

<version>${org.springframework-version}</version>

</dependency>


(중략)


<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->

<dependency>

    <groupId>com.zaxxer</groupId>

    <artifactId>HikariCP</artifactId>

    <version>3.4.2</version>

</dependency>


<dependency>

<groupId>com.oracle.database.jdbc</groupId>

<artifactId>ojdbc8</artifactId>

<version>19.3.0.0</version>

</dependency>    


* 파일명: pom.xml


* 참고 - MySQL 연동할 때


아래의 코드는 pom.xml에 넣어준다.


<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->

<dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    <version>8.0.21</version>

</dependency>




6. Project의 Properties의 Java Build Path 내 Libraries의 JRE 버전 바꾸기


pom.xml은 maven 환경에 대한 자바 버전 설정이었는데, 근본적인 Build Path에 관한 속성을 변경하는 작업이다.


[JAVA JDK 버전 오류]

오류 : Resource specification not allowed here for source level below 1.7



그림 5. Properties 클릭하기


프로젝트를 클릭한다.

오른쪽 버튼을 누른 후, Properties를 클릭한다.




그림 6. Java Build Path 설정하기 - Libraries


JRE System Library 1.6 버전을 Remove한다.

Add Library를 클릭하여 버전을 1.7 버전 이상으로 올려준다.



7. root-context.xml 수정하기


-> src/main/webapp/spring/root-context.xml에 있음.



그림 7. root-context.xml 파일 작업내용


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Root Context: defines shared resources visible to all other web components -->

<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">

<!-- Oracle 9 이상으로 작성. -->

<!-- 오라클 9 이후에 oracle.jdbc.driver.OracleDriver는 중단되었음.  -->

<!-- oracle.jdbc.pool.OracleDataSource -->

<!-- jdbc:oracle:thin:@localhost:1521:orcl -->


  <property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>

<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"></property> 

<property name="username" value="사용자계정명"></property>

<property name="password" value="비밀번호"></property>

</bean>

<bean id="datasource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">

<constructor-arg ref="hikariConfig"></constructor-arg>

</bean>

</beans>



파일명: root-context.xml (Oracle 11 이상) - 태스트 확인: Oracle 18g


* [첨부(Attachments)]

root-context-oracle.zip



* 참고 - MySQL 연동(root-context.xml)


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Root Context: defines shared resources visible to all other web components -->

<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:{포트번호}/{DB명}?serverTimezone=UTC"></property> 

<property name="username" value="사용자 계정명"></property>

<property name="password" value="비밀번호"></property>

</bean>

<bean id="datasource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">

<constructor-arg ref="hikariConfig"></constructor-arg>

</bean>

</beans>


파일명: root-context.xml(mysql 버전)


* [첨부(Attachments)]

root-context-mysql.zip



* 정정: jdbc:mysql://localhost:3306/web?serverTimezone=UTC&characterEncoding=utf8



8. servlet-context.xml 파일 수정하기


servlet-context.xml 파일을 수정해준다.


파일 경로: /src/main/webapp/WEB-INF/spring/appServlet



그림 8. servlet-context.xml - 수정된 모습


<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/mvc"

xmlns:util="http://www.springframework.org/schema/util"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:beans="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->

<annotation-driven />


<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->

<resources mapping="/resources/**" location="/resources/" />


<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<beans:property name="prefix" value="/WEB-INF/views/" />

<beans:property name="suffix" value=".jsp" />

</beans:bean>

<!-- 추가(Hikara4 -->

<!-- <context:property-placeholder location="classpath:/db.properties" />  -->

<util:properties id="props" location="classpath:/db.properties" />     

<context:component-scan base-package="com.springMVC.web.controller" />

</beans:beans>


파일명: servlet-context.xml


* [첨부(Attachments)]

servlet-context.zip




9. /src/main/resources/db.properties 만들기


Spring MVC 프로젝트로 작성하였으면, Resources 폴더는 생성되어 있을 것이다.

없다면, 별도로 만들어야 한다.


db.properties 파일은 존재하지 않기 때문에 따로 만들어줘야 한다.



그림 9. 파일 만들기


resources 폴더를 클릭한 후 오른쪽 버튼을 클릭한다.

New->File을 클릭한다.



그림 10. 프로젝트 구성 - dbProperties


jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl

dataSourceClassName=oracle.jdbc.OracleDriver

dataSource.user={username}

dataSource.password={password}

cachePrepStmts=true

prepStmtCacheSize=250

prepStmtCacheSqlLimit=2048


파일명: db.properties (oracle 버전)


[첨부(Attachments)]

db-properties-oracle.zip


jdbcUrl=jdbc:mysql://localhost:3306/web?serverTimezone=UTC

dataSourceClassName=com.mysql.cj.jdbc.Driver

dataSource.user={UserName}

dataSource.password={Password}

cachePrepStmts=true

prepStmtCacheSize=250

prepStmtCacheSqlLimit=2048


파일명: db.properties (mysql버전)


[첨부(Attachments)]

db-properties-mysql.zip



* 2부에서 만나요.


초기 셋팅은 이 정도면 끝났으니, 2부에서 연재하도록 하겠다.


[Spring-Framework] 11. Spring MVC - HikariCP 3.4.2, Oracle 19g 연동하기(Properties, Java) - (2), 2020-09-23 14:28

https://yyman.tistory.com/1411


반응형

+ Recent posts