GORM 对象关系未加载到异步块中
GORM Object Relation is not loaded in an async block
我使用 Grails GPaars 创建一个异步块。
在构建配置中:
compile 'org.codehaus.gpars:gpars:1.2.1'
compile 'org.codehaus.jsr166-mirror:jsr166y:1.7.0'
我定义了一个助手Class:
class TaskService {
private ForkJoinPool pool = new ForkJoinPool()
/**
* Executes the given closure in a new thread.
* @param args is a map of arguments to be used in the async closure.
* @return
*/
def executeAsync(args, closure = null) {
if(!closure) {
closure = args
args = null
}
GParsPool.withExistingPool(pool) { closure.callAsync(args) }
}
}
现在在我的控制器中:
TrackingEmail tEmail = TrackingEmail.get(trackingEmailId)
Device targetDevice = tEmail.device
前者的工作方式是device
从TrackingEmail 对象中检索。
现在我尝试在异步块中做同样的事情:
taskService.executeAsync(trackingEmailId: trackingEmailId) { data ->
TrackingEmail tEmail = TrackingEmail.get(data.trackingEmailId)
Device targetDevice = tEmail.device
}
在此异步块中,仅 tEmail
从数据库中检索。第二行没有执行。
如何在异步块中获取关系对象?
我认为您不应该直接使用 GPars 进行 GORMing。在这种情况下,您必须自己照顾 transactions/sessions:
taskService.executeAsync(trackingEmailId: trackingEmailId) { data ->
Device.withTransaction{ tx ->
TrackingEmail tEmail = TrackingEmail.get(data.trackingEmailId)
Device targetDevice = tEmail.device
}
}
在频繁并行调用的情况下,这会给你带来糟糕的性能。
我建议看一下 Asynchronous Programming in Grails,它使用扩展的 GPars
我使用 Grails GPaars 创建一个异步块。
在构建配置中:
compile 'org.codehaus.gpars:gpars:1.2.1'
compile 'org.codehaus.jsr166-mirror:jsr166y:1.7.0'
我定义了一个助手Class:
class TaskService {
private ForkJoinPool pool = new ForkJoinPool()
/**
* Executes the given closure in a new thread.
* @param args is a map of arguments to be used in the async closure.
* @return
*/
def executeAsync(args, closure = null) {
if(!closure) {
closure = args
args = null
}
GParsPool.withExistingPool(pool) { closure.callAsync(args) }
}
}
现在在我的控制器中:
TrackingEmail tEmail = TrackingEmail.get(trackingEmailId)
Device targetDevice = tEmail.device
前者的工作方式是device
从TrackingEmail 对象中检索。
现在我尝试在异步块中做同样的事情:
taskService.executeAsync(trackingEmailId: trackingEmailId) { data ->
TrackingEmail tEmail = TrackingEmail.get(data.trackingEmailId)
Device targetDevice = tEmail.device
}
在此异步块中,仅 tEmail
从数据库中检索。第二行没有执行。
如何在异步块中获取关系对象?
我认为您不应该直接使用 GPars 进行 GORMing。在这种情况下,您必须自己照顾 transactions/sessions:
taskService.executeAsync(trackingEmailId: trackingEmailId) { data ->
Device.withTransaction{ tx ->
TrackingEmail tEmail = TrackingEmail.get(data.trackingEmailId)
Device targetDevice = tEmail.device
}
}
在频繁并行调用的情况下,这会给你带来糟糕的性能。
我建议看一下 Asynchronous Programming in Grails,它使用扩展的 GPars