|
| 1 | +package com.wypl.redisembeddeddomain; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import org.springframework.beans.factory.annotation.Value; |
| 6 | +import org.springframework.context.annotation.Configuration; |
| 7 | +import org.springframework.context.annotation.Profile; |
| 8 | + |
| 9 | +import com.wypl.redisembeddeddomain.redis.*; |
| 10 | + |
| 11 | +import jakarta.annotation.PostConstruct; |
| 12 | +import jakarta.annotation.PreDestroy; |
| 13 | +import lombok.extern.slf4j.Slf4j; |
| 14 | +import redis.embedded.RedisServer; |
| 15 | + |
| 16 | +@Slf4j |
| 17 | +@Profile({"default", "local", "test"}) |
| 18 | +@Configuration |
| 19 | +public class EmbeddedRedisConfig { |
| 20 | + private static final String OS_NAME = System.getProperty("os.name"); |
| 21 | + |
| 22 | + @Value("${spring.data.redis.port}") |
| 23 | + private int redisPort; |
| 24 | + |
| 25 | + private RedisServer redisServer; |
| 26 | + |
| 27 | + @PostConstruct |
| 28 | + private void start() throws IOException { |
| 29 | + RedisAvailablePortFind findAvailablePortUtils = getRedisAvailablePortFind(); |
| 30 | + |
| 31 | + int port = findAvailablePortUtils.isRedisRunning(redisPort) |
| 32 | + ? findAvailablePortUtils.findAvailablePort(redisPort) |
| 33 | + : redisPort; |
| 34 | + log.info("Embedded Redis Running Port : [{}]", port); |
| 35 | + |
| 36 | + redisServer = new RedisServer(port); |
| 37 | + redisServer.start(); |
| 38 | + } |
| 39 | + |
| 40 | + @PreDestroy |
| 41 | + private void stop() throws IOException { |
| 42 | + if (redisServer != null) { |
| 43 | + redisServer.stop(); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private RedisAvailablePortFind getRedisAvailablePortFind() { |
| 48 | + if (OS.MAC.contains(OS_NAME)) { |
| 49 | + return new RedisAvailablePortFindForMac(); |
| 50 | + } else if (OS.WINDOWS.contains(OS_NAME)) { |
| 51 | + return new RedisAvailablePortFindForWindows(); |
| 52 | + } else if (OS.UBUNTU.contains(OS_NAME)) { |
| 53 | + return new RedisAvailablePortFindForUbuntu(); |
| 54 | + } else if (OS.LINUX.contains(OS_NAME)) { |
| 55 | + return new RedisAvailablePortFindForLinux(); |
| 56 | + } else if (OS.DEBIAN.contains(OS_NAME)) { |
| 57 | + return new RedisAvailablePortFindForDebian(); |
| 58 | + } |
| 59 | + throw new IllegalArgumentException("Unsupported OS : " + OS_NAME); |
| 60 | + } |
| 61 | +} |
0 commit comments