我正在使用groovy处理批处理作业,我打算使用groovy的@Memoize注释来缓存域对象,但问题是到期,我想在作业完成时使缓存失效。有没有办法告诉groovy从代码中缓存缓存?
答案 0 :(得分:1)
根据the docs,@Memoized
仅包含最大值和保护缓存大小参数。
由于封面下的AST将通过Closure::memoize
创建memoize机制,你可以使用map和memoized闭包来模拟它,这些闭包可以被处理:
class Job {
def log = []
def repoBase = [
sum: { a, b ->
log << "sum $a and $b"
a + b
},
multiply: { a, b ->
log << "multiply $a and $b"
}
]
def repo
def startJob() {
repo = repoBase.collectEntries { key, value ->
[(key): value.memoize()]
} as Expando
}
def withJob(Closure c) {
startJob()
c.delegate = repo
c.delegateStrategy = Closure.DELEGATE_FIRST
c(this)
repo = null
}
}
并测试:
j = new Job()
j.withJob {
multiply 3, 4
multiply 3, 4
multiply 8, 8
sum 9, 9
sum 1, 2
sum 9, 9
}
assert j.log == [
"multiply 3 and 4",
"multiply 8 and 8",
"sum 9 and 9",
"sum 1 and 2"
]