본문 바로가기
spring/spring 기타

Spring Boot H2 사용 시 DataSource 접근하기 (feat. IntelliJ, Kotlin)

by Empering 2020. 6. 23.
반응형

H2

Spring Boot 프로젝트 개발 시 임베디드 모드의 H2 DB를 주로 사용합니다. 빠르고 간편하긴 하지만 어플리케이션의 임베디드로 구동되기 때문에 실제 애플리케이션에서 동작하고 있는 H2 DB에 접근 할 수 없습니다. 물론 H2 Console 이라는 WEB으로 접근 가능한 툴이 있긴하지만 TCP 서버를 이용해 좀 더 쉽게 사용하는 방법을 알아봅니다.


build.gradle 수정

gradle 의 dependencies 설정 중에 h2 관련 부분을 runtimeOnly 에서 implementation 으로 변경합니다.

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    developmentOnly("org.springframework.boot:spring-boot-devtools")
    // runtimeOnly("com.h2database:h2")
    implementation("com.h2database:h2")
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
    }
}

 

maven인 경우 pom.xml 수정

maven 의 dependencies 설정 중에 h2 scope를 runtime에서 compile 으로 변경합니다.

<dependencies>
	<!-- .... -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>compile</scope>
        </dependency>
</dependencies>

 

application.properties 수정

H2 datasource 정보를 설정합니다. (hikari 사용)

spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
spring.datasource.hikari.username=sa
spring.datasource.hikari.password=

 

H2 TcpServer Bean 등록

H2 datasource 설정 값을 통해 TCP 서버를 spring-boot의 bean으로 등록합니다.

포트번호는 9092로 지정하고 실행 시 tcpAlloOthers 옵션을 추가로 부여합니다.

기본적으로 H2는 TCP를 실행 할 때 외부의 접속을 허용하지 않습니다. -tcpAllowOthers 옵션을 주면 tcpPort를 이용해 외부에서 접속가능하게 됩니다.

kotlin

import com.zaxxer.hikari.HikariDataSource
import org.h2.tools.Server
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import javax.sql.DataSource

@Configuration
@Profile("!prod")
class H2ServerConfiguration {

    @Bean
    @ConfigurationProperties("spring.datasource.hikari")
    fun dataSource(): DataSource {
        Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092").start()
        return HikariDataSource()
    }
}

 

java

import com.zaxxer.hikari.HikariDataSource;
import org.h2.tools.Server;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class H2ServerConfiguration {

	@Bean
	@ConfigurationProperties("spring.datasource.hikari")
	public DataSource dataSource() throws SQLException {
		Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "8089").start();
		return new HikariDataSource();
	}
}

 

외부연결 설정

외부 DB Client를 통해 접속 가능한지 테스트 합니다.

connenction type 을 remote로 지정합니다.

host는 localhost 로 설정합니다.

port, user 정보는 application.properties 에 설정한 값을 설정합니다.

url 부분에 마지막 database 부분에 mem:databasename 을 설정합니다.

 

마지막으로 Test Connection을 통해 문제가 없는지 테스트 해봅니다.

 

IntelliJ Database 추가

DataSource 탭 > + (혹은 Alt + Insert) > Data Source > H2 선택

Data Source 설정 (바로 윗단계 참고해서 정보 입력)

IntelliJ Database 에 추가되어 스키마 확인 가능

반응형

댓글