RedisTestConfiguration.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package cn.iocoder.dashboard.config;
  2. import com.github.fppt.jedismock.RedisServer;
  3. import org.redisson.spring.starter.RedissonAutoConfiguration;
  4. import org.springframework.boot.autoconfigure.AutoConfigureBefore;
  5. import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
  6. import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
  7. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.context.annotation.Lazy;
  11. import java.io.IOException;
  12. @Configuration(proxyBeanMethods = false)
  13. @Lazy(false) // 禁用懒加载,因为需要保证 Redis Server 必须先启动
  14. @EnableConfigurationProperties(RedisProperties.class)
  15. @AutoConfigureBefore({RedisAutoConfiguration.class, RedissonAutoConfiguration.class}) // 在 Redis 自动配置前,进行初始化
  16. public class RedisTestConfiguration {
  17. // /**
  18. // * 创建模拟的 Redis Server 服务器
  19. // */
  20. // @Bean(initMethod = "start", destroyMethod = "stop")
  21. // public RedisServer redisServer(RedisProperties properties) throws IOException {
  22. // return new RedisServer(properties.getPort());
  23. // }
  24. /**
  25. * 创建模拟的 Redis Server 服务器
  26. */
  27. @Bean(destroyMethod = "stop")
  28. public RedisServer redisServer(RedisProperties properties) throws IOException {
  29. RedisServer redisServer = new RedisServer(properties.getPort());
  30. // TODO 芋艿:一次执行多个单元测试时,貌似创建多个 spring 容器,导致不进行 stop。这样,就导致端口被占用,无法启动。。。
  31. try {
  32. redisServer.start();
  33. } catch (Exception ignore) {}
  34. return redisServer;
  35. }
  36. }