How to flush the cache

2019-03-02 02:25发布

问题:

In Apps Script I need a way to flush the cache regardless of key. Alternatively I need a way to find all the keys which are currently cached.

When we cache items we create the key based on a number of dynamic properties so we can't be sure what keys are in the cache at any one time.

Is there a way to do either of the above in AppsScript? Do I need to write out my keys to a log somewhere and then when I want to flush it just do remove all on my saved list of keys?

I've looked at the documentation here: https://developers.google.com/apps-script/reference/cache/cache-service but can't find anything so I'm not too hopeful.

Just wondered if anyone else has a solution for knowing what keys are in the cache?

回答1:

No way to do it like that. A better way to invalidate the cache is to store a version inside each cached object and keep the version in scriptProperties too. Whenever you read from the cache ignore it if its version is lower than your global version from scriptproperties. To invalidate the cache(s) simply increment your version from scriptProperties.



回答2:

Cache is faster than properties? Don't think so, check out this:

function propertiesUser() { // 1272.0 , 1135.0
  var value = { a: 'a', b: 'b' }
  var key = 'ab';
  PropertiesService.getUserProperties().setProperty(key, value);
  var i = 0;
  var t = Date.now();
  while (i<100) {
    Logger.log( PropertiesService.getUserProperties().getProperty(key))
    i++
  }
  Logger.log( Date.now()-t);
}

function propertiesScript() { // 1190.0
  var value = { a: 'a', b: 'b' }
  var key = 'ab';
  PropertiesService.getScriptProperties().setProperty(key, value);
  var i = 0;
  var t = Date.now();
  while (i<100) {
    Logger.log( PropertiesService.getScriptProperties().getProperty(key))
    i++
  }
  Logger.log( Date.now()-t);
}

function cache() { // 4141.0
  var value = { a: 'a', b: 'b' }
  var key = 'ab';
  CacheService.getUserCache().put(key, JSON.stringify(value))
  var i = 0;
  var t = Date.now();
  while (i<100) {
    Logger.log( CacheService.getUserCache().get(key) )
    i++
  }
  Logger.log( Date.now()-t);
}