- getDocumentCache()
- getScriptCache()
- getUserCache()
Gets the cache instance scoped to the script. Script caches are common to all users of the script. Use these to store information that is not specific to the current user.CacheServide 最多儲存 1,000 筆,超過 1,000 筆的話會保留 expirationInSeconds 最長的 900 筆資料
CRUD Sample Code
直接請 AI 產出紀錄
/**
* 示範 Google Apps Script 的 CacheService 混合寫入操作
* 包含 putAll (批量新增)、put (單筆新增)、getAll (批量讀取)、刪除與驗證
* * @returns {void}
*/
function demoCacheServiceMixedCRUD() {
// 1. 初始化 ScriptCache
const cache = CacheService.getScriptCache();
// 2. 使用 putAll() 批量新增三筆資料
// 將快取資料整理成一個 Object (KeyValue)
const batchData = {
'user_01': 'Alice',
'user_02': 'Bob',
'user_03': 'Charlie'
};
// 寫入批次資料,設定存活時間為 600 秒 (預設值)
cache.putAll(batchData, 600);
console.log('✅ 已使用 putAll() 成功新增三筆資料至 Cache。');
// 3. 使用 put() 追加新增單一筆資料
const singleKey = 'user_04';
cache.put(singleKey, 'David', 600);
console.log(`✅ 已使用 put() 成功追加一筆資料至 Cache:${singleKey}`);
// 4. 取得全部資料 (Read)
// 將批次寫入的 keys 與單筆寫入的 key 合併成一個陣列來查詢
const allKeysToFetch = ['user_01', 'user_02', 'user_03', 'user_04'];
const allData = cache.getAll(allKeysToFetch);
console.log('🔍 取得目前的資料狀態:', allData);
// 5. 移除一筆資料 (Delete)
const targetToRemove = 'user_02'; // 準備移除 Bob
cache.remove(targetToRemove);
console.log(`🗑️ 已執行移除動作,目標:${targetToRemove}`);
// 6. 取得上一筆移除資料,驗證該筆資料已不存在
const removedData = cache.get(targetToRemove);
if (removedData === null) {
console.log(`⚠️ 驗證成功:${targetToRemove} 已經被移除 (查詢結果為 null)。`);
} else {
console.log(`❌ 錯誤:${targetToRemove} 依然存在,值為:`, removedData);
}
}
put(key, value, expirationInSeconds)- key:最多 250 字元
- value:每一筆資料最大是 100KB
- expirationInSeconds:預設值為 600 秒 (10 分鐘) ,最少為 1 秒、最長為 21,600 秒 (6 小時),指定的到期時間僅供參考,如果快取大量資料,系統可能會提前移除快取資料 (有 1,000 筆快取限制)













