使用 Memcache

本頁說明如何使用 Google Cloud 控制台設定及監控應用程式的 Memcache 服務。也說明如何使用 App Engine Memcache Go API 設定和擷取快取的值。如要進一步瞭解 Memcache,請參閱 Memcache 總覽

設定 Memcache

  1. 前往 Google Cloud 控制台的「Memcache」頁面。
    前往「Memcache」頁面
  2. 選取您要使用的 Memcache 服務層級:

    • 「共用」(預設):免費的服務層級,提供最理想的快取容量。
    • 「專屬」:依 GB 時數快取量收費,為應用程式指派專屬的固定快取容量。

    進一步瞭解 Memcache 總覽中可用的服務類別。

匯入 Go API

如要匯入 memcache 套件,請按照下列步驟操作:

import "google.golang.org/appengine/memcache"

對值進行快取及擷取

對值進行快取

使用 Add() 寫入鍵值 (僅限鍵不含任何值的情況):

item := &memcache.Item{
        Key:   "[KEY]",
        Value: []byte("[VALUE]"),
}
memcache.Add(c, item)

其中 cappengine.Context

如要進一步瞭解 Add 和其他用於設定資料值的函式,請參閱 Memcache API 參考資料

查詢快取的值

使用 Get() 取得特定鍵項目:

memcache.Get(ctx, "[KEY]")

如要進一步瞭解 Get 和其他用於查詢資料值的函式,請參閱 Memcache API 參考資料

範例

下列範例示範如何使用 Go API 新增、設定及取得 Memcache 值。

假設 ctxappengine.Context

// Create an Item
item := &memcache.Item{
	Key:   "lyric",
	Value: []byte("Oh, give me a home"),
}
// Add the item to the memcache, if the key does not already exist
if err := memcache.Add(ctx, item); err == memcache.ErrNotStored {
	log.Infof(ctx, "item with key %q already exists", item.Key)
} else if err != nil {
	log.Errorf(ctx, "error adding item: %v", err)
}

// Change the Value of the item
item.Value = []byte("Where the buffalo roam")
// Set the item, unconditionally
if err := memcache.Set(ctx, item); err != nil {
	log.Errorf(ctx, "error setting item: %v", err)
}

// Get the item from the memcache
if item, err := memcache.Get(ctx, "lyric"); err == memcache.ErrCacheMiss {
	log.Infof(ctx, "item not in the cache")
} else if err != nil {
	log.Errorf(ctx, "error getting item: %v", err)
} else {
	log.Infof(ctx, "the lyric is %q", item.Value)
}

在 Google Cloud 控制台中監控 Memcache

  1. 前往 Google Cloud 控制台的「Memcache」頁面。
    前往「Memcache」頁面
  2. 查看下列報表:
    • 「Memcache service level」(Memcache 服務等級):顯示應用程式使用的是共用或專屬服務等級。如果您是專案的擁有者,則可以在兩個服務等級之間切換。進一步瞭解服務等級
    • 命中率:顯示從快取提供服務的資料要求百分比,以及從快取提供服務的資料要求原始數量。
    • 快取的項目
    • 「Oldest item age」(最舊項目時間長度):最舊快取項目已存在的時間。請注意,項目的存在時間長度會在每次使用 (無論是讀取或寫入) 項目時重設。
    • 「Total cache size」(總快取大小)
  3. 您可以採取下列任何動作:

    • 新增鍵:將新的鍵新增至快取。
    • 尋找鍵:擷取現有鍵。
    • 清除快取:從快取中移除所有鍵/值組合。
  4. (僅限專屬 Memcache) 查詢「熱門鍵」清單。

    • 「熱門鍵」是指 Memcache 中每秒查詢次數 (QPS) 超過 100 的鍵。
    • 此清單最多可包含 100 個熱門鍵,依照 QPS 由高至低排序。

後續步驟