【问题标题】:How to load datasource configuration from external file in grails 3.1.8?如何从 grails 3.1.8 中的外部文件加载数据源配置?
【发布时间】:2018-03-09 16:58:37
【问题描述】:

我正在编写一个 grails 3.1.8 应用程序。我的数据源写在 application.groovy 文件中。

我想从外部文件加载数据源配置,如用户名、密码、数据库。有没有办法在 grails 3+ 版本中做到这一点。

这是我在 application.groovy 中的数据源配置:-

hibernate {
    cache {
        queries = false
        use_second_level_cache = true
        use_query_cache = false
        region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
    }
}

dataSource {
    pooled = true
    jmxExport = true
    dialect = 'org.hibernate.dialect.PostgreSQLDialect'
    driverClassName = 'org.postgresql.Driver'
    username = 'postgres'
    password = 'postgres'
    properties = {
        jmxEnabled = true
        initialSize = 5
        maxActive = 50
        minIdle = 5
        maxIdle = 25
        maxWait = 10000
        maxAge = 10 * 60000
        timeBetweenEvictionRunsMillis = 5000
        minEvictableIdleTimeMillis = 60000
        validationQuery = "SELECT 1"
        validationQueryTimeout = 3
        validationInterval = 15000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = false
        ignoreExceptionOnPreLoad = true
        jdbcInterceptors = "ConnectionState;StatementCache(max=200)"
        defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED // safe default
        abandonWhenPercentageFull = 100 // settings are active only when pool is full
        removeAbandonedTimeout = 120
        removeAbandoned = true
        logAbandoned = false // causes stacktrace recording overhead, use only for debugging
    }
}

environments {
    development {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
    test {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
    production {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
}

【问题讨论】:

    标签: grails groovy datasource properties-file grails-3.0


    【解决方案1】:

    您可以使用external-config Grails 插件并在您的外部配置文件中定义配置。

    grails.config.locations = [
            "file:///etc/app/myconfig.groovy"
    ]
    

    然后在myconfig.groovy中定义数据源配置

    【讨论】:

      【解决方案2】:

      您可以使用以下实现从文件系统加载外部配置文件。

      此示例为每个环境(开发/生产/测试)定义了一个外部配置文件的单独路径。

       environments {
           development {
                grails.config.locations = [
                      "file:///home/<CONFIG_FILE_LOCATION_DIR>/myconfig_developement.groovy" //for Unix based systems
                ]
           }
           production {
                grails.config.locations = [
                      "file:///home/<CONFIG_FILE_LOCATION_DIR>/myconfig_production.groovy" // for Unix based systems
                ]
           }
      }
      

      将你的数据库配置放入myconfig_developement.groovy如下:

      dataSource {
          dbCreate = 'update'
          url = "jdbc:postgresql://localhost:5432/testdb"
          logSql = true
      }
      

      【讨论】:

        【解决方案3】:

        这是对我有用的解决方案,您可以尝试。

        此解决方案适用于 grails 3.0+

        首先需要添加如下依赖:

        编译'org.grails.plugins:external-config:1.1.2'

        然后需要创建外部配置groovy文件例如:

        db-config.groovy

        然后需要将该配置文件放在应用程序目录或 tomcat 库之外。例如:

        D:\apache-tomcat-8.0.47\lib

        然后需要从 application.groovy 中读取配置文件。 在 application.groovy 中需要为每个环境放置以下代码行:

        grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']

        grails.config.locations = ['file:///D:/apache-tomcat-8.0.47/lib/db-config.groovy']

        如果您在系统中设置环境变量为 CATALINA_HOME,则可以使用 ${catalina.home}。除了你必须使用我展示的直接路径。

        所以您的 application.groovy 将如下:

        > environments {
        >      development {
        >          grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']
        >      }
        >      production {
        >           grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']
        >           ]
        >      }
        > }
        

        您的 db-config.groovy 文件将包含以下几行:

        >     dataSource {
        >       username = <DB_USER_NAME>
        >       password = <DB_PASSWORD>
        >       dbCreate = 'update'
        >       url = <DB_URL>
        >       logSql = true
        >     }
        

        您可以为每个环境使用不同的 db-config.groovy 文件。

        【讨论】:

          【解决方案4】:

          您可以使用此解决方案(对我有用,使用 grails 3.1.x)

          grails-app/init/Application.groovy:

          class Application extends GrailsAutoConfiguration implements EnvironmentAware {
              static void main(String[] args) {
                  GrailsApp.run(Application, args)
              }
          
              @Override
              void setEnvironment(Environment environment) {
                  def path = "/etc/grails-app-config.properties"
                  def file = new File(path)
          
                  if(file.exists()) {
                      def config = new ConfigSlurper().parse(file.text)
                      environment.propertySources.addFirst(new MapPropertySource(grails.util.Environment.getCurrent().name, config))
                  }
              }
          }
          

          您可以使用环境变量作为配置路径:

          System.getenv(ENV_CONF_FILE_VAR)
          

          grails-app-config.properties:

          dataSource.dbCreate='update'
          dataSource.driverClassName='com.mysql.jdbc.Driver'
          dataSource.url='jdbc:mysql://localhost:5432/testdb'
          dataSource.username='user'
          dataSource.password='pass'
          com.test='test'
          com.numTest=4
          

          【讨论】:

          • 属性会覆盖application.yml吗?
          【解决方案5】:

          我正在使用 grails 3.3.11,这是我为从外部文件/源加载数据库配置所做的:


          application.yaml:

          将所有值保留为空,以便它们可以被外部源覆盖

          dataSource:
            pooled: true
            driverClassName: "com.microsoft.sqlserver.jdbc.SQLServerDriver"
            url:
            username:
            password:
            loggingSql: true
          

          现在有两种方法可以运行应用程序,

          1. bootRun(如下配置)
          2. 可运行的 jar 或 war,java -jar --spring.config.location=file:external.properties

          bootRun (build.gradle)

          def Properties localBootRunProperties() {
              Properties p = new Properties()
              p.load(new FileInputStream("path to external.properties"))
              return p
          }
          bootRun {
              doFirst {
                  bootRun.systemProperties = localBootRunProperties()
              }
              ...
          }
          

          现在,external.properties 文件应该具有完全相同的配置来覆盖 application.yaml 值

          dataSource.url=
          dataSource.username=
          dataSource.password=
          

          就是这样。享受吧。

          【讨论】:

            猜你喜欢
            • 2010-11-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-10-15
            • 1970-01-01
            • 2014-08-07
            • 2014-03-14
            相关资源
            最近更新 更多