[Spring Boot] H2 connection refused 문제 해결

김우경·2021년 5월 13일
0

트러블💥

목록 보기
4/6
  1. build.gradle의 h2 dependency runtimeOnlyimplementation
dependencies {
	...
	implementation 'com.h2database:h2'
	...
}
  1. application.properties 의 local datasource를 hikari.datasource로 수정

: H2 db를 tcp로 우회하여 외부에서 접근하기 위해서 Hikari의 jdbc-url로 설정합니다.

spring:
  profiles: local
  datasource:
    hikari:
      jdbc-url: jdbc:h2:mem:test
      driver-class-name: org.h2.Driver
      username: sa
      password:
			
...
  1. H2 tcp server 활성화시키기
package com.ollacare.api.comm.config;
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", "9092").start();
        return new HikariDataSource();
    }
}

기본적으로 H2는 TCP를 실행 할 때 외부 접속을 허용하지 않기 때문에 -tcpAllowOthers 옵션으로 외부에서 접속 가능하게 설정합니다.

  1. 연결 확인하기
    인텔리제이에서 바로 확인도 가능하지만 dbeaver로 연결해보았습니다.

성공😎😎😎

출처

https://empering.tistory.com/entry/Spring-Boot-H2-사용-시-DataSource-접근하기-feat-IntelliJ-Kotlin

https://dico.me/java/articles/241/ko

profile
Hongik CE

0개의 댓글