我正在编写一个 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 3.0+
首先需要添加以下依赖:
compile '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 文件。
关于grails - 如何在 grails 3.1.8 中从外部文件加载数据源配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46460845/