管理配置策略
- 环境变量:
- 原理:在容器启动时设置不同的环境变量,每个环境(开发、测试、生产)根据自身需求设置特定值。例如,数据库连接字符串可以通过
DB_CONNECTION_STRING
环境变量传递,日志级别可以通过 LOG_LEVEL
环境变量设置。
- 优点:简单直接,容器编排工具(如 Docker Compose、Kubernetes)都支持设置环境变量,方便在不同环境快速切换配置。
- 缺点:对于复杂的配置,环境变量可能变得冗长且难以管理。
- 配置文件:
- 原理:为每个环境准备独立的配置文件(如
application - dev.properties
、application - test.properties
、application - prod.properties
)。这些文件包含特定环境的数据库连接、日志级别等配置信息。在容器构建或启动时,将相应的配置文件挂载到容器内指定位置。
- 优点:配置清晰,易于管理和维护,适合复杂配置场景。
- 缺点:需要额外处理配置文件的版本控制和部署过程中的文件替换。
- 配置中心:
- 原理:使用诸如 Spring Cloud Config、Apollo 等配置中心。将所有环境的配置集中存储在配置中心,应用程序在启动时从配置中心拉取对应环境的配置。
- 优点:动态更新配置,无需重启应用程序,方便统一管理和监控配置。
- 缺点:增加了系统架构的复杂性,需要额外部署和维护配置中心服务。
Kotlin 代码中读取配置
- 使用环境变量:
val dbConnectionString = System.getenv("DB_CONNECTION_STRING")
val logLevel = System.getenv("LOG_LEVEL")
- 使用配置文件:
- 依赖库:例如,使用
kotlin - config
库。首先在 build.gradle.kts
中添加依赖:
implementation("io.github.config4k:config4k:0.5.0")
- 代码示例:假设配置文件为
application.properties
,内容为 db.connection.string=jdbc:mysql://localhost:3306/mydb
和 log.level=INFO
import io.github.config4k.loadConfig
import java.io.File
data class AppConfig(
val dbConnectionString: String,
val logLevel: String
)
val configFile = File("application.properties")
val config = loadConfig<AppConfig>(configFile)
val dbConnectionString = config.dbConnectionString
val logLevel = config.logLevel
- 使用配置中心(以 Spring Cloud Config 为例,结合 Spring Boot in Kotlin):
- 添加依赖:在
build.gradle.kts
中添加 Spring Cloud Config 相关依赖:
implementation("org.springframework.cloud:spring - cloud - starter - config")
- 配置引导属性:在
bootstrap.properties
中配置连接到配置中心的信息,例如:
spring.application.name=my - app
spring.cloud.config.uri=http://config - server - address:port
spring.cloud.config.profile=dev
- 代码中读取配置:通过
@Value
注解或 Environment
对象获取配置。例如:
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class MyApp : CommandLineRunner {
@Value("\${db.connection.string}")
lateinit var dbConnectionString: String
@Value("\${log.level}")
lateinit var logLevel: String
override fun run(vararg args: String?) {
println("DB Connection String: $dbConnectionString")
println("Log Level: $logLevel")
}
}
fun main(args: Array<String>) {
runApplication<MyApp>(*args)
}