我使用 Grails GPaars 创建异步 block 。
在构建配置中:
compile 'org.codehaus.gpars:gpars:1.2.1'
compile 'org.codehaus.jsr166-mirror:jsr166y:1.7.0'
我定义了一个辅助类:
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) }
}
}
现在在 Controller 中我这样做:
TrackingEmail tEmail = TrackingEmail.get(trackingEmailId)
Device targetDevice = tEmail.device
前者的工作方式是从 TrackingEmail 对象中检索设备
。
现在我尝试在异步 block 中执行相同的操作:
taskService.executeAsync(trackingEmailId: trackingEmailId) { data ->
TrackingEmail tEmail = TrackingEmail.get(data.trackingEmailId)
Device targetDevice = tEmail.device
}
在此异步 block 中,仅从数据库检索tEmail
。第二行不执行。
如何在异步 block 中获取关系对象?
最佳答案
我认为您不应该直接使用 GPar 进行 GORMing。在这种情况下,您必须自己处理事务/ session :
taskService.executeAsync(trackingEmailId: trackingEmailId) { data ->
Device.withTransaction{ tx ->
TrackingEmail tEmail = TrackingEmail.get(data.trackingEmailId)
Device targetDevice = tEmail.device
}
}
在频繁并行调用的情况下,这会给你带来糟糕的性能。
我建议看看Asynchronous Programming in Grails ,它使用扩展的 GPars
关于java - GORM 对象关系未加载到异步 block 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32640777/