gpt4 book ai didi

grails - 在 Grails 中定义可选(多个)数据源

转载 作者:行者123 更新时间:2023-12-02 01:03:21 25 4
gpt4 key购买 nike

我目前正在使用 Grails 2.3.11 开发 Grails 插件,并熟悉使用多个数据源。但现在我希望该插件提供的域对象可以使用不同的数据源(由于性能原因,所有数据都可以存储在不同的数据库中)。

问题是,第二个数据源是可选的,这意味着用户可以在 tomcat 中定义第二个数据源(可通过 JNDI 访问),但不是必须这样做。这是很重要的一点:用户可以在 servlet 容器中定义第二个数据源,Grails 应用程序必须检查是否有第二个数据源可用!

更具体地说:我有一个域类:

class MyDomain {

static mapping = {
datasource('optionalDS')
}
}

我的数据源.groovy:

dataSource {
jndiName = "..."
}

dataSource_optionalDS {
jndiName = "..."
}

问题是,如果用户没有为该可选数据源配置 JNDI 名称,这将会失败(因为它是可选的,他不必这样做)。

我尝试创建一个委托(delegate)数据源:

class OptionalDataSource extends DelegatingDataSource {

...
// the main purpose is to check, if the optional DS
// can be created using JNDI. If this fails, the default
// DS is used
setTagetDataSource(dataSource)
...

}

在我的插件描述符中:

def doWithSpring = {
dataSource_optionalDS(OptionalDataSource) {
// set default DS in case optional can not be created
dataSource = ref('dataSource')
}
}

此解决方案的问题是,数据源可选DS不可用。如果我尝试读取数据,即 MyDomain.findAll(),我会收到以下错误:

Methond on class MyDomain was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

我不明白为什么,因为我可以这样定义默认的数据源。

所以,我的问题是:如何在 Grails 中定义可选的数据源?

最佳答案

如何在 DataSource.groovy 中查找 JNDI dataSource,然后如果它存在,则声明您的可选 dataSource。类似于以下内容

    //default dataSource
dataSource {
jndiName = "..."
}

//optional dataSource
//let's first lookup the JNDI dataSource
def jndiDataSource

try {
jndiDataSource = InitialContext.doLookup("...")
}
catch(NamingException ne) {}

//now if jndiDataSource exists we can declare the optional dataSource
if(jndiDataSource) {
dataSource_optionalDS {
jndiName = "..."
}
}

我正在寻找一种替代的轻量级方法,用于仅检查 JNDI dataSource 是否存在,而不是查找它。但没有运气。

关于grails - 在 Grails 中定义可选(多个)数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com