Skip to content

Commit

Permalink
Merge pull request #127 from f-lab-edu/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
pak0426 authored Jul 1, 2024
2 parents 965a8a2 + b7ac65c commit 4cf8a5a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'mysql:mysql-connector-java:8.0.33'
implementation 'org.redisson:redisson-spring-boot-starter:3.31.0'
implementation 'com.github.codemonstur:embedded-redis:1.4.3'

compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.mini.joymall.commons.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.StringUtils;
import redis.embedded.RedisServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Profile("test")
@Configuration
public class EmbeddedRedisConfig {
@Value("${spring.data.redis.port}")
private int redisPort;

private RedisServer redisServer;

@PostConstruct
public void redisServer() throws IOException {
int port = isRedisRunning()? findAvailablePort() : redisPort;
redisServer = new RedisServer(port);
redisServer.start();
}

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

private boolean isRedisRunning() throws IOException {
return isRunning(executeGrepProcessCommand(redisPort));
}

public int findAvailablePort() throws IOException {

for (int port = 10000; port <= 65535; port++) {
Process process = executeGrepProcessCommand(port);
if (!isRunning(process)) {
return port;
}
}

throw new IllegalArgumentException("Not Found Available port: 10000 ~ 65535");
}

private Process executeGrepProcessCommand(int port) throws IOException {
String command = String.format("netstat -nat | grep LISTEN|grep %d", port);
String[] shell = {"/bin/sh", "-c", command};
return Runtime.getRuntime().exec(shell);
}

private boolean isRunning(Process process) {
String line;
StringBuilder pidInfo = new StringBuilder();

try (BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()))) {

while ((line = input.readLine()) != null) {
pidInfo.append(line);
}

} catch (Exception e) {
}

return !StringUtils.hasText(pidInfo.toString());
}
}

0 comments on commit 4cf8a5a

Please sign in to comment.