Last active
March 28, 2020 14:37
-
-
Save nomyfan/5ec0d8f13b6f8e6faff1d14ac212377e to your computer and use it in GitHub Desktop.
Spring Boot config loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.conf | |
import io.lettuce.core.RedisClient | |
import io.lettuce.core.RedisURI | |
import org.slf4j.LoggerFactory | |
import java.io.FileOutputStream | |
import java.lang.reflect.UndeclaredThrowableException | |
import java.nio.ByteBuffer | |
import java.nio.file.Paths | |
import java.time.Duration | |
class ConfigLoadingException(message: String) : Exception(message) | |
class ConfigLoaderNotFoundException(message: String) : Exception(message) | |
interface ConfigLoader { | |
@Throws(ConfigLoadingException::class) | |
fun load(resourceName: String, args: Array<String>) | |
} | |
class ConfigLoaderFactory { | |
companion object { | |
fun loaderOf(type: String): ConfigLoader { | |
return when (type) { | |
"redis" -> RedisConfigLoader() | |
else -> throw ConfigLoaderNotFoundException("Cannot find the config loader typed $type") | |
} | |
} | |
} | |
} | |
private class RedisConfigLoader : ConfigLoader { | |
override fun load(resourceName: String, args: Array<String>) { | |
val logger = LoggerFactory.getLogger(RedisConfigLoader::class.java) | |
val classLoader = RedisConfigLoader::class.java.classLoader | |
val url = classLoader.getResource(resourceName) | |
?: throw ConfigLoadingException("Cannot find the resource named $resourceName") | |
val path = Paths.get(url.toURI()) | |
logger.info("Resource file path is $path") | |
val channel = FileOutputStream(path.toFile()).channel | |
val host = args[0] | |
val port = args[1].toInt() | |
val password = args[2].toCharArray() | |
val key = args[3] | |
val redisURI = RedisURI(host, port, Duration.ofSeconds(5)).apply { this.password = password } | |
val redisClient = RedisClient.create(redisURI) | |
val conn = redisClient.connect() | |
logger.info("Connected to Redis") | |
val value = conn.sync().get(key) | |
if (value.isNullOrEmpty()) { | |
throw ConfigLoadingException("Cannot read resource from redis with key named $key") | |
} | |
val buffer = ByteBuffer.wrap(value.toByteArray()) | |
channel.write(buffer) | |
channel.close() | |
conn.close() | |
redisClient.shutdown() | |
logger.info("Replaced the resource file successfully!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment