AWS ElastiCache-新增 TTL



TTL 也稱為生存時間。它用於充分利用延遲載入策略和直寫策略。這兩個策略已在前幾章中討論過。直寫可確保資料始終是最新的,但對於空節點可能會失敗,並且可能向快取記憶體儲入多餘的資料。透過向每次寫入中新增生存時間 (TTL) 值,我們可以獲得每種策略的優勢,並在很大程度上避免向快取記憶體中塞入多餘的資料。

TTL 工作原理

生存時間 (TTL) 是一個整數值,指定鍵到期前的秒數。當應用程式嘗試讀取已過期的鍵時,它將被視為找不到該鍵,這意味著將針對該鍵查詢資料庫並更新快取記憶體。但這並不能保證某個值不是陳舊的,但它會阻止資料變得過於陳舊,並要求偶爾從資料庫重新整理快取記憶體中的值。

TTL 示例

以下程式碼給出瞭如何透過使用函式來實現 TTL 的一個示例。它使用 Memcached 中 set 命令來獲取幫助。

直寫策略的程式碼

save_customer(customer_id, values)
   customer_record = db.query(""UPDATE Customers WHERE id = {0}"", customer_id, values)
   cache.set(customer_id, customer_record, 300)

   return success

延遲載入策略的程式碼

get_customer(customer_id)
   customer_record = cache.get(customer_id)
    
   if (customer_record != null)
      if (customer_record.TTL < 300)
         return customer_record        // return the record and exit function
            
   // do this only if the record did not exist in the cache OR
   // the TTL was >= 300, i.e., the record in the cache had expired.
   customer_record = db.query(""SELECT * FROM Customers WHERE id = {0}"", customer_id)
   cache.set(customer_id, customer_record, 300)  // update the cache
   return customer_record          
廣告