我想使用memoise
包和cache_filesystem
来缓存长时间运行的函数,以便在闪亮的应用程序中使用。这几乎完美地工作,问题是输入是一个列表对象,其中包含一个(其中包括)将改变的数据库连接。我想在输入对象中忽略这个元素。
数据库连接将在会话之间发生变化,但我需要memoise
才能查看输入中的id
元素,而不是列表中的其他元素。有没有办法可以做到这一点?我看过...
的论点,但这似乎只是进一步限制,而不是放松。
简化示例如下:
localCache = cache_filesystem("memoiseCache/")
input1_1 = list(id = "id1", dbConn = 100)
input1_2 = list(id = "id1", dbConn = 101)
testFun=function(input) {
print("Running the function")
return(100)
}
library(memoise)
testFun.mem = memoise(testFun)
# This will run the function for the initial time - CORRECT
> testFun.mem(input1_1)
[1] "Running the function"
[1] 100
# This will now fetch the cached result - CORRECT
> testFun.mem(input1_1)
[1] 100
# I need this to ignore the dbConn element and instead fetch the cached result
> testFun.mem(input1_2)
[1] "Running the function"
[1] 100
编辑:我的函数的输入实际上指向静态DB,因此缓存结果没有问题,静态DB指向的是由id
元素定义的,但是可以对同一个DB进行不同的连接。这些功能可以任意复杂化。例如:
function(dbInputObj){
<Many table joins and aggregations>
<Some logic and conditions>
<More table joins>
return(result)
}
您可以编写包装函数来隐藏差异。我无法看到您的应用程序如何使用简化代码。
您是否使用不同的dbConn
连接到同一个数据库?您是否尝试在数据库查询后缓存数据库查询或某些计算?
如果dbConn
可能不同,我认为缓存数据库查询不是一个好主意。您应该从数据库获取更新数据,而不是缓存它。
如果要在数据库查询后缓存计算,只需先获取值,然后仅使用值记住计算函数,而不是数据库连接。