在您的 DataSource.groovy 文件中,您需要创建另一个数据源以指向 DB2。您可能可以为此克隆您的数据源定义,例如。
http://grails.github.io/grails-doc/2.3.9/guide/conf.html#multipleDatasources
dataSource_db2 {
pooled = true
jmxExport = true
driverClassName = "org.postgresql.Driver"
username = "XXX"
password = "YYY"
//noinspection GrReassignedInClosureLocalVar
dialect = PostgreSQLDialect
autoreconnect = true
useUnicode = true
characterEncoding = "utf-8"
tcpKeepAlive = true
//noinspection GroovyAssignabilityCheck
properties {
// See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
initialSize = 5
maxActive = 50
minIdle = 5
maxIdle = 25
maxWait = 10000
maxAge = 10 * 60000
timeBetweenEvictionRunsMillis = 1000 * 60 * 1 // 1 min
minEvictableIdleTimeMillis = 1000 * 60 * 5 // 5 min
numTestsPerEvictionRun = 3
validationQuery = 'SELECT 1'
validationQueryTimeout = 3
validationInterval = 15000
testOnBorrow = true
testWhileIdle = false
testOnReturn = false
defaultTransactionIsolation = Connection.TRANSACTION_READ_COMMITTED
removeAbandoned = true
removeAbandonedTimeout = 20 // 20s is a long query
logAbandoned = true // causes stacktrace recording overhead, use only for debugging
// use JMX console to change this setting at runtime
// the next options are jdbc-pool specific
// http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes
// https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/tomcat/jdbc/pool/PoolConfiguration.html
jmxEnabled = true
// ResetAbandonedTimer resets the timer upon every operation on the connection or a statement.
// ConnectionState caches the auto commit, read only and catalog settings to avoid round trips to the DB.
jdbcInterceptors = "ConnectionState;ResetAbandonedTimer;SlowQueryReportJmx(threshold=10000)"
abandonWhenPercentageFull = 25 // settings are active only when pool is full
}
}
要将其用于数据库连接访问,您可以将 javax.sql.DataSource 注入到您的服务、控制器、域类或其他 Grails Artefakts 中。
例如。
import javax.sql.DataSource
import groovy.sql.GroovyResultSet
import groovy.sql.Sql
MyService {
DataSource dataSource_db2
def doQuery(String query) {
new Sql(dataSource_db2).rows(query)
}
}
要让域对象使用您的 db2 dataSource for GORM,请添加到您的域对象“映射”块:
static mapping = {
datasource 'db2'
}
如果你想要 JNDI 支持,你也可以在你的 resources.groovy 中添加类似这样的东西:
xmlns jee: "http://www.springframework.org/schema/jee"
jee.'jndi-lookup'(id: "dataSource", 'jndi-name': "java:comp/env/jdbc/db1")
jee.'jndi-lookup'(id: "dataSource_db2", 'jndi-name': "java:comp/env/jdbc/db2")