使用 Memcache

本页面介绍如何使用 Google Cloud Console 为您的应用配置和监控 Memcache 服务,还说明了如何使用 App Engine Memcache Go API 来设置和检索缓存的值。要详细了解 Memcache,请参阅 Memcache 概览

配置 memcache

  1. 转到 Google Cloud Console 中的 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 Console 中监控 Memcache

  1. 转到 Google Cloud Console 中的 Memcache 页面。
    转到 Memcache 页面
  2. 查看以下报告:
    • Memcache 服务等级:显示您的应用使用的服务等级为“共享”还是“专用”。如果您是项目的所有者,则可以在两者之间切换。详细了解服务等级
    • 命中率:显示从缓存处理的数据请求的百分比,以及从缓存处理的数据请求的原始数量。
    • 缓存中的内容
    • 最早的内容的存续时间:最早缓存的内容的存续时间。请注意,每次使用内容时(无论是读取还是写入)都会重置其存续时间。
    • 总缓存大小
  3. 您可以执行以下任何操作:

    • 新建键:向缓存添加新键。
    • 查找键:检索现有键。
    • 清空缓存:移除缓存中的所有键值对。
  4. (仅限专用 Memcache 使用)查看热键列表。

    • “热键”是 Memcache 中收到的每秒查询次数 (QPS) 超过 100 的键。
    • 该列表包含最多 100 个热键,按 QPS 的多少降序排列。

后续步骤