package com.roomroot; import com.roomroot.web.core.config.EmbeddedRedisCondition; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import redis.embedded.RedisServer; import java.io.IOException; @Configuration @Conditional(EmbeddedRedisCondition.class) public class EmbeddedRedisConfig { private final int redisPort; private final String maxMemory; private RedisServer redisServer; public EmbeddedRedisConfig( @Value("${custom.embedded-redis.port}") int redisPort, @Value("${custom.embedded-redis.max-memory}") String maxMemory ) { this.redisPort = redisPort; this.maxMemory = maxMemory; } @PostConstruct public void startEmbeddedRedis() throws IOException { try { redisServer = new RedisServer(redisPort); // 可变参数追加redis配置 redisServer.start( ); System.out.println("===== 内嵌Redis启动成功,端口:" + redisPort + " ====="); } catch (Exception e) { e.printStackTrace(); System.err.println("内嵌Redis启动失败!端口:" + redisPort); } } @PreDestroy public void stopEmbeddedRedis() throws IOException { if (redisServer != null && redisServer.isActive()) { redisServer.stop(); System.out.println("===== 内嵌Redis已停止 ====="); } } }