嵌入式Redis的SmartLifeCycle

时间:2019-11-22 16:37:07

标签: spring-boot kotlin spring-data-redis

我正在尝试对嵌入式Redis(https://github.com/kstyrc/embedded-redis)进行优雅的实现。

但是当有几个测试类时,我遇到了这个问题:

Caused by: java.lang.RuntimeException: Can't start redis server. Check logs for details.
at redis.embedded.AbstractRedisInstance.awaitRedisServerReady(AbstractRedisInstance.java:61)
at redis.embedded.AbstractRedisInstance.start(AbstractRedisInstance.java:39)
at redis.embedded.RedisServer.start(RedisServer.java:9)
at com.wck.commons.redis.EmbeddedRedisLifecycle.safeStart(EmbeddedRedisLifecycle.kt:41)
at com.wck.commons.redis.EmbeddedRedisLifecycle.start(EmbeddedRedisLifecycle.kt:25)
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182)
... 101 more

我的实现是这样的:

@Component
class EmbeddedRedisLifecycle : SmartLifecycle {

   private val log = LoggerFactory.getLogger(this::class.java)

   private val server = RedisServer()

   override fun isRunning() = server.isActive

   override fun start() = server.safeStart()

   override fun isAutoStartup() = true

   override fun stop(callback: Runnable) {
       stop().also { callback.run() }
   }

   override fun stop() {
       server.takeIf { isRunning }?.stop()
   }

   override fun getPhase() = 0

   private fun RedisServer.safeStart() = try {
       start()
       log.info("Starting embedded Redis server at ${ports()}")
   } catch (e: RuntimeException) {
       throw e
   }
}

非常感谢!

0 个答案:

没有答案