Skip to content

Commit

Permalink
feat: embedded redis 설정 파일 작성
Browse files Browse the repository at this point in the history
  • Loading branch information
EunjiShin committed Aug 25, 2024
1 parent 0d82f11 commit 7ecb17d
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 2 deletions.
2 changes: 1 addition & 1 deletion application/src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ server:
spring:
# 서브모듈 profile
profiles:
active: dev
active: local
group:
local:
- jpa
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,75 @@
package org.depromeet.spot.infrastructure.redis;

public class EmbeddedRedisConfig {}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import redis.embedded.RedisServer;

@Slf4j
@Configuration
@Profile("local | test")
@RequiredArgsConstructor
public class EmbeddedRedisConfig {

private final RedisProperties redisProperties;

private RedisServer redisServer;

@PostConstruct
public void redisServer() throws IOException {
int port = isRedisPortUsed() ? findAvailablePort() : redisProperties.port();
log.info("embedded redis port = {}", port);
redisServer = new RedisServer(port);
redisServer.start();
}

@PreDestroy
public void stopRedis() {
if (redisServer != null) {
redisServer.stop();
}
}

private boolean isRedisPortUsed() throws IOException {
Process process = getProcessListeningOnPort(redisProperties.port());
return isRunningProcess(process);
}

private Process getProcessListeningOnPort(final int port) throws IOException {
String command = "lsof -i :" + port + " | grep LISTEN";
String[] shell = {"/bin/sh", "-c", command};
return Runtime.getRuntime().exec(shell);
}

private boolean isRunningProcess(Process process) {
try (BufferedReader input =
new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line = input.readLine();
if (line == null) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}

private int findAvailablePort() throws IOException {
for (int port = 10000; port <= 65535; port++) {
Process process = getProcessListeningOnPort(port);
if (!isRunningProcess(process)) {
return port;
}
}
throw new IllegalArgumentException("10000 ~ 65535 사이에서 사용 가능한 포트가 없습니다.");
}
}

0 comments on commit 7ecb17d

Please sign in to comment.