【问题标题】:Store Google API results in cache indefinitely将 Google API 结果无限期存储在缓存中
【发布时间】:2021-04-12 09:33:03
【问题描述】:

我正在尝试让下面的代码(Google 表格的自定义函数)将 API 查询的结果无限期地存储在缓存中。

// The cache key for "New York" and "new york  " should be same
const md5 = (key = '') => {
  const code = key.toLowerCase().replace(/\s/g, '');
  return Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, key)
    .map((char) => (char + 256).toString(16).slice(-2))
    .join('');
};

const getCache = (key) => {
  return CacheService.getDocumentCache().get(md5(key));
};

// Store the results for 6 hours
const setCache = (key, value) => {
  const expirationInSeconds = 6 * 60 * 60;
  CacheService.getDocumentCache().put(md5(key), value, expirationInSeconds);
};

const GOOGLEMAPS_DISTANCE = (origin, destination, mode = 'driving') => {

  const key = ['distance', origin, destination, mode].join(',');
  // Is result in the internal cache?
  const value = getCache(key);
  // If yes, serve the cached result
  if (value !== null) return value;
  const { routes: [data] = [] } = Maps.newDirectionFinder()
    .setOrigin(origin)
    .setDestination(destination)
    .setMode(mode)
    .getDirections();
  if (!data) {
    GOOGLEMAPS_DISTANCE;
  }
  const { legs: [{ distance: { text: distance } } = {}] = [] } = data;
  // Store the result in internal cache for future
  setCache(key, distance);
  return distance;
};

使用 Google Maps API,该函数能够返回 Google 表格中指定的两个位置之间的距离,并将结果保存在缓存中 6 小时。如果新输入的位置之前已经被检索和缓存过,则将检索缓存的结果,否则将发送新的 API 查询。

根据Class Cache上的Google's documentation,使用put调用,结果最多只能在内部缓存中存储6小时:

expirationInSeconds:

整数:

值在缓存中保留的最长时间,以秒为单位。最小值为 1 秒,最大值为 21600 秒(6 小时)。

不过,我读到了 Place IDs (documentation),这可能是 6 小时限制的一种解决方法。

来自Places API Policies 文档:

请注意,用于唯一标识地点的地点 ID 不受缓存限制。因此,您可以无限期地存储地点 ID 值。地点 ID 在地点 API 响应的 place_id 字段中返回。

我发现的另一种可能的解决方法是在Google Properties Service Documentation 中使用Properties,但我似乎无法在代码中实现它。

如果有人愿意回复并帮助我,我将不胜感激。

【问题讨论】:

    标签: javascript google-apps-script google-sheets google-api google-places-api


    【解决方案1】:

    你有两个选择:

    • 使用属性无限期地存储数据。
    • 继续使用缓存并设置一个 触发每 5 小时(缓存过期前)恢复缓存 其他 6 小时的价值。

    https://developers.google.com/apps-script/reference/properties

    要使用属性,请为此更改您的 getCache 和 setCache 函数:

    const getProperty = (key) => {
      var scriptProperties = PropertiesService.getScriptProperties();
      return scriptProperties.getProperty(md5(key));
    };
    
    const setProperty = (key, value) => {
      var scriptProperties = PropertiesService.getScriptProperties();
      scriptProperties.setProperty(md5(key), value);
    };
    

    【讨论】:

    • 感谢您的回复。我也读过这个,但是由于我对编程很陌生,所以我不知道如何使用我拥有的代码来完成这项工作。您能帮我使用属性服务调整我的代码吗?
    猜你喜欢
    • 2019-01-27
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    相关资源
    最近更新 更多