Usa Memcache
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En esta página, se describe cómo configurar y supervisar el servicio de Memcache para tu aplicación con la consola de Google Cloud . También se explica cómo usar la API de Go de Memcache de App Engine para configurar y recuperar valores almacenados en caché. Para obtener más información sobre Memcache, consulta la Descripción general de Memcache.
Configura Memcache
- Ve a la página de Memcache en la Google Cloud consola.
Ir a la página de Memcache
Selecciona el nivel de servicio de Memcache que desees usar:
- Compartido (predeterminado): es gratuito y proporciona capacidades de caché sobre la base del "mejor esfuerzo".
- Dedicado: se factura por GB por hora de tamaño de caché y proporciona una capacidad de caché fija asignada exclusivamente a tu aplicación.
Puedes aprender más sobre clases de servicio disponibles en la Descripción general de Memcache.
Importa la API de Go
Haz esto para importar el paquete memcache
:
Almacena valores en caché y recupéralos
Almacena un valor en caché
Usa Add()
a fin de escribir un valor para una clave solo si no existe ningún valor dedicado a ella:
item := &memcache.Item{
Key: "[KEY]",
Value: []byte("[VALUE]"),
}
memcache.Add(c, item)
donde c
es appengine.Context
.
Obtén más información sobre Add
y otras funciones para establecer valores en Referencia de la API de Memcache.
Busca valores almacenados en caché
Usa Get()
para obtener el elemento de una clave determinada:
memcache.Get(ctx, "[KEY]")
Obtén más información sobre Get
y otras funciones para buscar valores en Referencia de la API de Memcache.
Ejemplo
En el ejemplo que aparece a continuación, se muestra cómo agregar, configurar y obtener valores de Memcache mediante la API de Go.
Supón que ctx
es appengine.Context
.
Supervisa Memcache en la Google Cloud consola
- Ve a la página de Memcache en la Google Cloud consola.
Ir a la página de Memcache
- Consulta los siguientes informes:
- Nivel de servicio de Memcache: Muestra si tu aplicación usa el nivel de servicio Compartido o Dedicado.
Si eres propietario del proyecto, puedes alternar entre ambos. Obtén más información sobre los niveles de servicio.
- Proporción de aciertos: Muestra el porcentaje de solicitudes de datos que se entregaron desde la caché y la cantidad de solicitudes de datos sin procesar que se entregaron desde la caché.
- Elementos en la caché.
- Edad del elemento más antiguo: Edad del elemento almacenado en caché más antiguo. Ten en cuenta que la edad de un elemento se restablece cada vez que se usa, ya sea en operaciones de lectura o de escritura.
- Tamaño total de caché
Puedes realizar cualquiera de las siguientes acciones:
- Clave nueva: agrégale una clave a la caché.
- Encontrar una clave: recupera una clave existente.
- Limpiar caché: quita todos los pares clave-valor de la caché.
(Solo para Memcache dedicada) Consulta la lista de claves populares.
- Las "claves populares" son claves que reciben más de 100 consultas por segundo (QPS) en Memcache.
- La lista incluye hasta 100 claves populares ordenadas de mayor a menor cantidad de QPS.
¿Qué sigue?
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-09-04 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eThis guide outlines how to configure and monitor the memcache service for applications using the Google Cloud console.\u003c/p\u003e\n"],["\u003cp\u003eThe document details how to utilize the App Engine memcache Go API to store and retrieve cached data through \u003ccode\u003eAdd()\u003c/code\u003e and \u003ccode\u003eGet()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eMemcache offers two service levels: Shared, which is free with best-effort capacity, and Dedicated, which offers fixed cache capacity and is billed by GB-hour.\u003c/p\u003e\n"],["\u003cp\u003eThe Google Cloud console's Memcache page provides reports on service level, hit ratio, item count, item age, total cache size, and hot keys (for dedicated memcache).\u003c/p\u003e\n"],["\u003cp\u003eThe guide provides instructions on how to import the memcache package and provides a code example of adding, setting, and getting memcache values.\u003c/p\u003e\n"]]],[],null,["# Using Memcache\n\nThis page describes how to configure and monitor the memcache service for your\napplication using the Google Cloud console. It also describes how to use the App Engine memcache Go API\nto set and retrieve cached values. To learn more about memcache,\nread the [Memcache Overview](/appengine/docs/legacy/standard/go111/memcache).\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| go\n| /services/access). If you are updating to the App Engine Go 1.12+ runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/go-differences) to learn about your migration options for legacy bundled services.\n\nConfiguring memcache\n--------------------\n\n1. Go to the Memcache page in the Google Cloud console. \n [Go to the Memcache page](https://console.cloud.google.com/appengine/memcache)\n2. Select the memcache service level you want to use:\n\n - **Shared** (default) - free and provides cache capacity on a best-effort basis.\n - **Dedicated** - billed by the GB-hour of cache size and provides a fixed cache capacity assigned exclusively to your application.\n\n Learn more about available service classes in [Memcache Overview](#service_levels).\n\nImporting the Go API\n--------------------\n\nTo import the `memcache` package: \n\n import \"google.golang.org/appengine/memcache\"\n\nCaching and retrieving values\n-----------------------------\n\n### Caching a value\n\nUse [`Add()`](/appengine/docs/legacy/standard/go111/reference/latest/memcache#google_golang_org_appengine_memcache_Add) to write a value for a key if and only if no value\nalready exists for the key: \n\n item := &memcache.Item{\n Key: \"[KEY]\",\n Value: []byte(\"[VALUE]\"),\n }\n memcache.Add(c, item)\n\nwhere `c` is an `appengine.Context`.\n\nLearn more about `Add` and other functions for setting values in [Memcache API\nReference](/appengine/docs/legacy/standard/go111/memcache/reference).\n\n### Looking up cached values\n\nUse [`Get()`](/appengine/docs/legacy/standard/go111/reference/latest/memcache#google_golang_org_appengine_memcache_Item_Get) to get the item for a given key: \n\n memcache.Get(ctx, \"[KEY]\")\n\nLearn more about `Get` and other functions for looking up values in [Memcache\nAPI Reference](/appengine/docs/legacy/standard/go111/memcache/reference).\n\n### Example\n\nThe following example demonstrates how to add, set, and get Memcache values\nusing the Go API.\n\nAssume that `ctx` is an `appengine.Context`. \n\n // Create an Item\n item := &memcache.Item{\n \tKey: \"lyric\",\n \tValue: []byte(\"Oh, give me a home\"),\n }\n // Add the item to the memcache, if the key does not already exist\n if err := memcache.Add(ctx, item); err == memcache.ErrNotStored {\n \tlog.Infof(ctx, \"item with key %q already exists\", item.Key)\n } else if err != nil {\n \tlog.Errorf(ctx, \"error adding item: %v\", err)\n }\n\n // Change the Value of the item\n item.Value = []byte(\"Where the buffalo roam\")\n // Set the item, unconditionally\n if err := memcache.Set(ctx, item); err != nil {\n \tlog.Errorf(ctx, \"error setting item: %v\", err)\n }\n\n // Get the item from the memcache\n if item, err := memcache.Get(ctx, \"lyric\"); err == memcache.ErrCacheMiss {\n \tlog.Infof(ctx, \"item not in the cache\")\n } else if err != nil {\n \tlog.Errorf(ctx, \"error getting item: %v\", err)\n } else {\n \tlog.Infof(ctx, \"the lyric is %q\", item.Value)\n }\n\nMonitoring memcache in the Google Cloud console\n-----------------------------------------------\n\n1. Go to the Memcache page in the Google Cloud console. \n [Go to the Memcache page](https://console.cloud.google.com/appengine/memcache) \n2. Look at the following reports:\n - **Memcache service level** : Shows if your application is using the Shared or Dedicated service level. If you are an owner of the project, you can switch between the two. Learn more about the [service levels](./#service_levels).\n - **Hit ratio**: Shows the percentage of data requests that were served from the cache, as well as the raw number of data requests that were served from the cache.\n - **Items in the cache**.\n - **Oldest item age**: The age of the oldest cached item. Note that the age of an item is reset every time it is used, either read or written.\n - **Total cache size**.\n3. You can take any of the following actions:\n\n - **New key**: Add a new key to the cache.\n - **Find a key**: Retrieve an existing key.\n - **Flush cache**: Remove all the key-value pairs from the cache.\n4. (Dedicated memcache only) Look through the list of **Hot keys**.\n\n - \"Hot keys\" are keys that receive more than 100 queries per second (QPS) in the memcache.\n - This list includes up to 100 hot keys, sorted by highest QPS.\n\nWhat's next\n-----------\n\n- Learn more about memcache in the [Memcache Overview](/appengine/docs/legacy/standard/go111/memcache).\n- Refer to the [Memcache API Reference](/appengine/docs/legacy/standard/go111/memcache/reference)."]]