如何为Spark Java提供动态数据库配置凭据?

时间:2017-05-13 19:34:48

标签: java gradle kotlin spark-java

我正在使用spark java构建一个简单的REST API。该项目使用Postgres DB进行存储,gradle作为构建系统。胖Jar部署在AWS

我有三个环境localstaging& production。对于每个胖jar创建,我想提供类似下面用于本地构建的特定配置:

    dbHost = "localhost"
    dbUsername = "myusername"
    dbPassword = "mypassword"
    database = "mydb"
    dbPort = "5432"

如何基于fatJar构建变体动态提供这些值?

1 个答案:

答案 0 :(得分:0)

我按照此示例github项目Kotlin-dev-proxy使用了.properties文件。

服务器读取名为app_environment的环境变量并使用适当的资源文件。

示例代码:

<强> DbConfig.kt

data class DbConfig(
        val dbHost: String,
        val dbUsername: String,
        val dbPassword: String,
        val dbName: String,
        val dbPort: Int)

<强> ServerSettings.kt

class ServerSettings(settings: String) {
    val resources = Properties()

    init {
        val fileUrl: URL = resources.javaClass.getResource("/$settings.properties")
                ?: throw FileNotFoundException("$settings.properties file not found")
        fileUrl.openStream().use { resources.load(it) }
    }

    fun printSettings() = resources.stringPropertyNames().forEach {
        println("Property: $it has value: '${resources[it]}'")
    }

    fun getString(key: String): String = resources[key]!! as String

    fun getInt(key: String): Int = (resources[key]!! as String).toInt()
}

<强> DbConfig.kt

fun provideDbConfig(): DbConfig {
        val settings = ServerSettings(System.getenv("app_environment"))
        settings.printSettings()

        return DbConfig(
                dbHost = settings.getString("dbHost"),
                dbUsername = settings.getString("dbUsername"),
                dbPassword = settings.getString("dbPassword"),
                dbName = settings.getString("dbName"),
                dbPort = settings.getInt("dbPort")
        )
    }

<强>资源/ develop.properties

# Local Db values
dbHost=localhost
dbUsername=postgresusername
dbPassword=postgrespassword
dbName=mydbname
dbPort=5432

在Amazon EBS中部署时,转到软件配置并为环境添加适当的环境变量(暂存/生产)。