스프링

 

https://github.com/brettwooldridge/HikariCP

 

 

	    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
	        <constructor-arg>
	            <bean class="com.zaxxer.hikari.HikariConfig">
	                <constructor-arg>
	                    <props>
	                        <prop key="jdbcUrl">${db.jdbcUrl}</prop>
	                        <prop key="username">${db.user}</prop>
	                        <prop key="password">${db.password}</prop>
	                    </props>
	                </constructor-arg>
	                <property name="driverClassName" value="${db.driver}"/>
	                <property name="maximumPoolSize" value="10" />	                
	                <property name="connectionTimeout"  value="300000" />
	                
	            </bean>
	        </constructor-arg>
	    </bean>

 

 

 

 

HikariCP 옵션

jdbcUrl, username, password는 너무 기본적인 내용이라 생략하겠습니다.

HikariCP설정의 시간 단위는 ms입니다.

 

ㅁ autoCommit: auto-commit설정 (default: true)

 

ㅁ connectionTimeout: pool에서 커넥션을 얻어오기전까지 기다리는 최대 시간, 허용가능한 wait time을 초과하면 SQLException을 던짐. 설정가능한 가장 작은 시간은 250ms (default: 30000 (30s))

 

ㅁ idleTimeout: pool에 일을 안하는 커넥션을 유지하는 시간. 이 옵션은 minimumIdle이 maximumPoolSize보다 작게 설정되어 있을 때만 설정. pool에서 유지하는 최소 커넥션 수는 minimumIdle (A connection will never be retired as idle before this timeout.). 최소값은 10000ms (default: 600000 (10minutes))

 

ㅁ maxLifetime: 커넥션 풀에서 살아있을 수 있는 커넥션의 최대 수명시간. 사용중인 커넥션은 maxLifetime에 상관없이 제거되지않음. 사용중이지 않을 때만 제거됨. 풀 전체가아닌 커넥션 별로 적용이되는데 그 이유는 풀에서 대량으로 커넥션들이 제거되는 것을 방지하기 위함임. 강력하게 설정해야하는 설정 값으로 데이터베이스나 인프라의 적용된 connection time limit보다 작아야함. 0으로 설정하면 infinite lifetime이 적용됨(idleTimeout설정 값에 따라 적용 idleTimeout값이 설정되어 있을 경우 0으로 설정해도 무한 lifetime 적용 안됨). (default: 1800000 (30minutes))

 

ㅁ connectionTestQuery: JDBC4 드라이버를 지원한다면 이 옵션은 설정하지 않는 것을 추천. 이 옵션은 JDBC4를 지원안하는 드라이버를 위한 옵션임(Connection.isValid() API.) 커넥션 pool에서 커넥션을 획득하기전에 살아있는 커넥션인지 확인하기 위해 valid 쿼리를 던지는데 사용되는 쿼리 (보통 SELECT 1 로 설정) JDBC4드라이버를 지원하지않는 환경에서 이 값을 설정하지 않는다면 error레벨 로그를 뱉어냄.(default: none)

 

ㅁ minimumIdle: 아무런 일을 하지않아도 적어도 이 옵션에 설정 값 size로 커넥션들을 유지해주는 설정. 최적의 성능과 응답성을 요구한다면 이 값은 설정하지 않는게 좋음. default값을 보면 이해할 수있음. (default: same as maximumPoolSize)

 

ㅁ maximumPoolSize: pool에 유지시킬 수 있는 최대 커넥션 수. pool의 커넥션 수가 옵션 값에 도달하게 되면 idle인 상태는 존재하지 않음.(default: 10)

 

ㅁ poolName: 이 옵션은 사용자가 pool의 이름을 지정함. 로깅이나 JMX management console에 표시되는 이름.(default: auto-generated)

 

ㅁ initializationFailTimeout: 이 옵션은 pool에서 커넥션을 초기화할 때 성공적으로 수행할 수 없을 경우 빠르게 실패하도록 해준다. 상세 내용은 한국말보다 원문이 더 직관적이라 생각되어 다음 글을 인용함.

This property controls whether the pool will “fail fast” if the pool cannot be seeded with an initial connection successfully. Any positive number is taken to be the number of milliseconds to attempt to acquire an initial connection; the application thread will be blocked during this period. If a connection cannot be acquired before this timeout occurs, an exception will be thrown. This timeout is applied after the connectionTimeout period. If the value is zero (0), HikariCP will attempt to obtain and validate a connection. If a connection is obtained, but fails validation, an exception will be thrown and the pool not started. However, if a connection cannot be obtained, the pool will start, but later efforts to obtain a connection may fail. A value less than zero will bypass any initial connection attempt, and the pool will start immediately while trying to obtain connections in the background. Consequently, later efforts to obtain a connection may fail. Default: 1

 

ㅁ readOnly: pool에서 커넥션을 획득할 때 read-only 모드로 가져옴. 몇몇의 database는 read-only모드를 지원하지 않음. 커넥션이 read-only로 설정되어있으면 몇몇의 쿼리들이 최적화 됨.(default: false)

 

ㅁ driverClassName: HikariCP는 jdbcUrl을 참조하여 자동으로 driver를 설정하려고 시도함. 하지만 몇몇의 오래된 driver들은 driverClassName을 명시화 해야함. 어떤 에러 메시지가 명백하게 표시 되지않는다면 생략해도됨.

 

ㅁ validationTimeout: valid 쿼리를 통해 커넥션이 유효한지 검사할 때 사용되는 timeout. 250ms가 설정될 수 있는 최솟값(default: 5000ms)

 

ㅁ leakDetectionThreshold: 커넥션이 누수 로그메시지가 나오기 전에 커넥션을 검사하여 pool에서 커넥션을 내보낼 수 있는 시간. 0으로 설정하면 leak detection을 이용하지않음. 최솟값 2000ms (default: 0)

Statement Cache

 

 많은 connection pool(including dbcp, vibur, c3p0)라이브러리들은 PreparedStatement caching을 지원하지만 HikariCP는 지원하지않는다. connection pool layer에서 PreparedStatements는 각 커넥션 마다 캐싱된다. 애플리케이션에서 250개의 공통적인 쿼리를 캐싱하고 있고 커넥션 pool size가 20이라면 database에 5000 쿼리 실행계획을 hold하고 있게된다. 대부분의 major database의 jdbc driver들은 이미 설정을 통해 Statement를 캐싱할 수 있다.(PostgreSQL, Oracle, Derby, MySQL, DB2 등등) 즉 우리가 원하는대로 250개의 쿼리 실행계획만 데이터베이스에 캐싱할 수 있음을 의미한다.(connection pool에 설정하는 것이 아닌 driver에 설정함으로써)

 

ps. Clever implementations do not even retain PreparedStatement objects in memory at the driver-level but instead merely attach new instances to existing plan IDs.

 

Log Statement Text / Slow Query Logging

Statement Cache와 마찬가지로 대부분의 vendor들은 driver단에서 해결

 

Performance Tips

MySQL Performance Tips

 

ㅁ prepStmtCacheSize: This sets the number of prepared statements that the MySQL driver will cache per connection. The default is a conservative 25. We recommend setting this to between 250-500.

ㅁ prepStmtCacheSqlLimit: This is the maximum length of a prepared SQL statement that the driver will cache. The MySQL default is 256. In our experience, especially with ORM frameworks like Hibernate, this default is well below the threshold of generated statement lengths. Our recommended setting is 2048.

ㅁ cachePrepStmts: Neither of the above parameters have any effect if the cache is in fact disabled, as it is by default. You must set this parameter to true.

ㅁ useServerPrepStmts: Newer versions of MySQL support server-side prepared statements, this can provide a substantial performance boost. Set this property to true.

 

A typical MySQL configuration for HikariCP might look something like this:

 

jdbcUrl=jdbc:mysql://localhost:3306/codingsquid

user=test

password=test

dataSource.cachePrepStmts=true

dataSource.prepStmtCacheSize=250

dataSource.prepStmtCacheSqlLimit=2048

dataSource.useServerPrepStmts=true

dataSource.useLocalSessionState=true

dataSource.rewriteBatchedStatements=true

dataSource.cacheResultSetMetadata=true

dataSource.cacheServerConfiguration=true

dataSource.elideSetAutoCommits=true

dataSource.maintainTimeStats=false

 

 

참고 자료 : https://github.com/brettwooldridge/HikariCP#configuration-knobs-baby

 

==========================================================================================

 

HikariCP property

HikariCP의 property 설정은 다음과 같습니다.

 

autoCommit (default : true)

connection이 종료되거나 pool에 반환될 때, connection에 속해있는 transaction을 commit 할지를 결정합니다.

 

readOnly (default : false)

database connection을 readOnly mode로 open합니다. 이 설정은 database에서 지원하지 않는다면 readOnly가 아닌 상태로 open되기 때문에, 지원되는 database 목록을 확인해보고 사용해야지 됩니다.

 

transactionIsolation (default : none)

java.sql.Connection 에 지정된 Transaction Isolation을 지정합니다. 지정된 Transaction Isoluation은 다음과 같습니다.

 

Connection.TRANSACTION_NONE : transaction을 지원하지 않습니다.

Connection.TRANSACTION_READ_UNCOMMITTED : transaction이 끝나지 않았을 때, 다른 transaction에서 값을 읽는 경우 commit되지 않은 값(dirty value)를 읽습니다.

Connection.TRANSACTION_READ_COMMITTED : transaction이 끝나지 않았을 때, 다른 transaction에서 값을 읽는 경우 변경되지 않은 값을 읽습니다.

Connection.TRANSACTION_REPEATABLE_READ : 같은 transaction내에서 값을 또다시 읽을 때, 변경되기 전의 값을 읽습니다. TRANSACTION_READ_UNCOMMITTED 와 같이 사용될 수 없습니다.

Connection.TRANSACTION_SERIALIZABLE : dirty read를 지원하고, non-repeatable read를 지원합니다.

기본값을 각 Driver vendor의 JDBCDriver에서 지원하는 Transaction Isoluation을 따라갑니다. (none으로 설정시.)

 

category (default : none)

connection에서 연결할 category를 결정합니다. 값이 설정되지 않는 경우, JDBC Driver에서 설정된 기본 category를 지정하게 됩니다.

 

connectionTimeout(default: 30000 - 30 seconds)

connection 연결시도시 timeout out값을 설정합니다. 이 시간내로 connection을 연결하는데 실패하면 SQLException을 발생합니다.

 

idleTimeout(default : 600000 - 10 minutes)

connection Pool에 의하여 확보된 connection의 maximum idle time을 결정합니다. connection Pool에 의하여 확보된 connection이 사용되지 않고, Pool에 의해서만 이 시간동안 관리된 경우, connection을 DB에 반환하게 됩니다. 값을 0으로 설정하는 경우, 확보된 connection을 절대 반환하지 않습니다.

 

maxLifetime(default : 1800000 - 30 minutes)

connection Pool에 의하여 확보된 connection의 최대 생명주기를 지정합니다. connection을 얻어낸지, 이 시간이상되면 최근에 사용하고 있던 connection일지라도, connection을 close시킵니다. 사용중에 있던 connection은 close 시키지 않습니다. (사용이 마쳐지면 바로 close 됩니다.) HikariCP에서는 이 값을 30~60 minutes 사이의 값을 설정하라고 강력권고합니다. 값을 0로 설정하는 경우 lifetime은 무제한이 됩니다.

 

leakDetectionThreshold (default : 0)

connectionPool에서 반환된 connection의 올바른 반환이 이루어졌는지를 확인하는 thread의 갯수를 지정합니다. 이 값을 0로 지정하는 경우, leak detection을 disable 시키게 됩니다. 만약에 또다른 connection pool을 사용하고 있다면, 다른 connection pool에서 만들어진 connection을 leak으로 판단하고 connection을 닫아버릴 수 있습니다.

 

jdbc4ConnectionTest (default : true)

connection을 맺은다음, Connection.isValid() method를 호출해서 connection이 정상적인지를 확인합니다. 이 property는 다음에 나올 connectionTestQuery에 매우 밀접한 영향을 받습니다.

 

connectionTestQuery (default : none)

Connection.isValid() method를 지원하지 않는 ‘legacy’ database를 위한 빠른 query를 지정합니다. (ex: VALUES 1) jdbc4ConnectionTest가 더 유용하기 때문에 사용하지 않는 것이 좋습니다.

 

connectionInitSql (default : none)

새로운 connection이 생성되고, Pool에 추가되기 전에 실행될 SQL query를 지정합니다.

 

dataSourceClassName (default : none)

JDBC driver에서 지원되는 dataSourceClassName을 지정합니다. 이 값은 driverClassName이 지정된 경우, 지정할 필요가 없습니다.

 

dataSource (default : none)

사용자가 만든 dataSource를 Pool에 의하여 wrapped하는 것을 원하는 경우, 이 값을 지정하여 사용합니다. HikariCP는 이 문자열을 이용해서 reflection을 통해 dataSource를 생성합니다. 이 값이 설정되는 경우, dataSourceClassName, driverClassName 과 같은 값들은 모두 무시 됩니다.

 

driverClassName

HikariCP에서 사용할 DriverClass를 지정합니다. 이 값이 지정되는 경우, jdbcUrl이 반드시 설정되어야지 됩니다.

 

jdbcUrl

jdbcUrl을 지정합니다. driverClassName이 지정된 경우, jdbcUrl을 반드시 지정해줘야지 됩니다.

 

minimumIdle (default : maximumPoolSize)

connection Pool에서 유지할 최소한의 connection 갯수를 지정합니다. HikariCP에서는 최고의 performance를 위해 maximumPoolSize와 minimumIdle값을 같은 값으로 지정해서 connection Pool의 크기를 fix하는 것을 강력하게 권장합니다.

 

# maximumPoolSize

connection Pool에서 사용할 최대 connection 갯수를 지정합니다. 이 부분은 운영환경과 개발환경에 매우 밀접하게 연결되는 부분으로, 많은 테스트 및 운영이 필요합니다.

 

username

Connection을 얻어내기 위해서 사용되는 인증 이름을 넣습니다.

 

password

username과 쌍이 되는 비밀번호를 지정합니다.

 

poolName (default : auto-generated)

logging과 JMX management에서 지정할 pool의 이름을 지정합니다.

 

registerMbeans (default : false)

JMX management Beans에 등록되는 될지 여부를 지정합니다.

 

[출처] HikariCP 옵션|작성자 하나자바

 

about author

PHRASE

Level 60  라이트

쉽고 간단하게 생각하고 단도직입적으로 사물을 직시할 때 천하의 진리를 얻을 수가 있다. -역경

댓글 ( 4)

댓글 남기기

작성

스프링 목록    more