在 SuiteScript 2.0 中使用 N/Cache 模块

Using the N/Cache Module in SuiteScript 2.0

我正在尝试在自定义模块中实现 N/cache 模块的使用,以跨包保留数据,而无需在每次需要数据时从远程源检索数据。所以我创建了这个来获取缓存数据:

function data_GetCachedData() {
    var remoteInfo = null;
    require(['N/cache'], function (cache) {
        var rmtCache = cache.getCache({
                name : _REMOTE_CACHE_NAME
            ,   scope : cache.Scope.PROTECTED
        });
        remoteInfo = rmtCache.get({
                key : _REMOTE_CACHE_INDEX
            ,   loader : comms_ObtainRemoteData(params)
        });
    });
    return JSON.parse(remoteInfo || "{ }");
}

然后我将其添加为加载程序:

function comms_ObtainRemoteData(params) {
    var remoteData = null;
    /*
        make HTTPS calls to remote server to add values to 'remoteData'
    */
    
    require(['N/cache'], function (cache) {
        var rmtCache = cache.getCache({
                name : _REMOTE_CACHE_NAME
            ,   scope : cache.Scope.PROTECTED
        });
        ptCache.put({
                key : _REMOTE_CACHE_INDEX
            ,   value : remoteData.values
            ,   ttl : (18 * 60 * 60)
        });
    });
    
    return remoteData.values;
}

但是,我添加了一些日志记录,每次调用 GetCachedData 时,它总是会触发加载程序。这有什么我想念的吗?因为据我所知,这样做应该很好,而不必总是调用加载程序。

我 运行 遇到了同样的问题,不得不切换代码。以下是您的代码示例:

var rmtCache = cache.getCache({
                name : _REMOTE_CACHE_NAME
            ,   scope : cache.Scope.PROTECTED
        });
if (rmtCache==null){
      rmtCache = remoteData.values
ptCache.put({
                key : _REMOTE_CACHE_INDEX
            ,   value : rmtCache 
            ,   ttl : (18 * 60 * 60)
        });
}

正如 NetSuite 明确指出的那样

A cached value is not guaranteed to stay in the cache for the full duration of the ttl value. The ttl value represents the maximum time that the cached value may be stored.

所以可能是由于资源紧缩(可能是由于所述帐户中有多个 scripts/caches 运行)或缓存因未及时 used/requested 而失效,它可能reset/cleared 从记忆中消失了。

此外,您是否在 test(Dev/Sandbox) 环境中测试您的脚本?由于与生产环境相比,测试环境的资源有限。

我在我的开发环境中多次遇到同样的问题,但它似乎在生产环境中运行良好。

您的脚本每次都在调用远程函数,因为您在带有参数的加载程序函数之后放置了括号。看到这一行 loader : comms_ObtainRemoteData(params) 如果您将其更改为 loader : comms_ObtainRemoteData 那么您应该没问题。 cache.get 的“loader”选项需要函数名,而不是函数调用的返回结果。