티스토리 뷰
토이 프로젝트를 개발하며 문득 다음과 같은 생각이 들었습니다.
"만약 다른 환경에서 내 프로젝트를 실행시키려면 MySQL, Redis 등 프로젝트에 필요한 의존성을 설치한 후에 실행해야 하는데 불편하지 않을까?"
또한 기업 과제를 할 때도 코드를 제출할 때 로컬 환경 구축 여부에 따라 큰 차이가 있을 것이라고 생각했습니다.
적어도 로컬 환경은 제약을 받지 않고 실행시킬 수 있어야 한다는 생각이 들었습니다. 코드를 받자마자 바로 실행시킬 수 있으면 코드를 받은 사람 입장에서는 다음 작업을 하기 편할 것입니다.
그래서 H2와 Embedded Redis를 사용해 로컬 환경을 구축하지 않더라도 Spring Boot 서버를 실행시킬 수 있도록 했습니다.
H2 설정
H2는 인메모리 DB로 Embedded mode(휘발성)와 Server mode(비휘발성)을 제공합니다.
장점
- 빠른 JDBC API를 제공
- 브라우저로 쉽게 접속 가능
- 설치 용량이 작음
단점
- 운영 환경과 DBMS가 다르면 문법 차이로 예상치 못한 오류가 발생할 수 있음
H2 적용
먼저 의존성을 추가해 줍니다.
runtimeOnly("com.h2database:h2")
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:~/${DB_NAME};MODE=MySQL # Server mode(비휘발성)
# url: jdbc:h2:mem:onBoard;MODE=MySQL # Embedded mode(휘발성)
username: username
password: password
h2:
console:
enabled: true # H2 콘솔을 활성화 시켜야 브라우저로 접속 가능
Spring Security를 사용 중이라면
다음과 같은 설정을 추가해야 합니다.
@Bean
fun filterChain(http: HttpSecurity): SecurityFilterChain {
return http
.csrf { it.disable() }
.headers { headers -> headers.frameOptions { frameOptions -> frameOptions.disable() } }
.authorizeHttpRequests { authorize ->
authorize
// h2 console
.requestMatchers("/h2-console/**").permitAll()
}
}
localhost:8080/h2-console에 접속 후 로그인을 성공하면 H2 db를 사용할 수 있습니다.
Embedded Redis 설정
Embedded Redis는 H2처럼 Redis를 구축하지 않더라도 애플리케이션 내에서 Redis를 실행할 수 있게 해 줍니다.
Embedded Redis 적용
먼저 의존성을 추가해 줍니다. Embedded Redis를 구현한 라이브러리가 많아서 가장 최근에 업데이트된 라이브러리를 사용했습니다.
implementation("com.github.codemonstur:embedded-redis:${embeddedRedisVersion}")
Redis 설정을 먼저 하겠습니다.
@Configuration
@EnableRedisRepositories
class RedisConfig(
private val redisProperties: RedisProperties,
) {
@Bean
fun redisConnectionFactory(): RedisConnectionFactory {
val redisConfiguration = RedisStandaloneConfiguration().apply {
hostName = redisProperties.host
port = redisProperties.port
redisProperties.password?.let {
password = RedisPassword.of(it)
}
}
return LettuceConnectionFactory(redisConfiguration)
}
}
@ConfigurationProperties(prefix = "spring.data.redis")
data class RedisProperties(
val host: String,
val port: Int,
val password: String?
)
@Profile("!prod")
@Configuration
class EmbeddedRedisConfig(
@Value("\${spring.data.redis.port}")
private val redisPort: Int,
) {
private lateinit var redisServer: RedisServer
@PostConstruct
fun startRedis() {
redisServer = RedisServer.newRedisServer()
.port(redisPort)
.setting("maxmemory 128M")
.build()
try {
redisServer.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
@PreDestroy
fun stopRedis() {
redisServer.stop()
}
}
@Profile("! prod")을 통해 운영 환경이 아닐 때만 Embedded Redis가 동작하도록 했습니다.
추가로 해당 블로그를 참고하면 맥/리눅스 환경에서만 사용하지 않는 포트로 Embedded Redis를 할당할 수 있습니다.
결과 확인
모든 세팅을 끝낸 다음 서버를 실행시키면 잘 실행되는 것을 확인할 수 있습니다.
마무리
H2와 Embedded Redis를 통해 별다른 세팅 없이 Spring Boot 서버를 실행시킬 수 있게 되었는데요.
이로써 아무런 세팅 없이 언제 어디서든지 코드를 실행시키고, 간편하게 통합 테스트를 진행할 수 있습니다.
한편으로는 로컬 DB(H2)와 운영 DB가 다른데 모든 기능을 완벽하게 대체할 수 있을지 의문이 들었습니다.
무조건 H2를 사용하기보다 프로젝트 성격에 맞게 DBMS를 선택해야 할 것 같습니다.
토이 프로젝트나 자주 공유되는 프로젝트에서는 H2를 사용해도 좋을 것 같다는 게 제 결론입니다!
'Spring' 카테고리의 다른 글
JPA N + 1 원인 및 해결 방법 (1) | 2024.08.02 |
---|---|
@Builder 조심하세요! (0) | 2024.07.29 |
Spring Boot Gradle 멀티 모듈 사용하기 (0) | 2024.07.29 |
Kotlin + Spring 프로젝트에 ktlint 도입하기 (1) | 2024.06.11 |
Webhook을 사용해 slack 메세지 보내기 (2) | 2024.06.04 |
- Total
- Today
- Yesterday
- multi module
- 성능 개선
- Spring Boot
- Slack
- 헥사고날 아키텍처
- IDE
- lombok
- ktlint
- H2
- 테스트 코드
- 계층형 아키텍처
- 자동화
- 인텔리제이
- Gradle
- N + 1
- propagation
- webhook
- lint
- transaction
- detekt
- JPA
- embedded redis
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |