Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, fornecemos exemplos de código em Java para usar a
API Memcache de nível inferior. Memcache
é um sistema de armazenamento em cache de objetos de memória distribuída de alto desempenho que fornece
acesso rápido aos dados armazenados em cache. Para saber mais sobre o Memcache, leia a
Visão geral do Memcache.
Uso síncrono
Exemplo de API de nível baixo que usa MemcacheService síncrono:
@SuppressWarnings("serial")// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.@WebServlet(name="MemcacheSync",description="Memcache: Synchronous",urlPatterns="/memcache/sync")publicclassMemcacheSyncCacheServletextendsHttpServlet{@OverridepublicvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsIOException,ServletException{Stringpath=req.getRequestURI();if(path.startsWith("/favicon.ico")){return;// ignore the request for favicon.ico}MemcacheServicesyncCache=MemcacheServiceFactory.getMemcacheService();syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));Stringkey="count-sync";byte[]value;longcount=1;value=(byte[])syncCache.get(key);if(value==null){value=BigInteger.valueOf(count).toByteArray();syncCache.put(key,value);}else{// Increment valuecount=newBigInteger(value).longValue();count++;value=BigInteger.valueOf(count).toByteArray();// Put back in cachesyncCache.put(key,value);}// Output contentresp.setContentType("text/plain");resp.getWriter().print("Value is "+count+"\n");}}
Uso assíncrono
Exemplo de API de nível inferior usando AsyncMemcacheService:
AsyncMemcacheServiceasyncCache=MemcacheServiceFactory.getAsyncMemcacheService();asyncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));Stringkey="count-async";byte[]value;longcount=1;Future<Object>futureValue=asyncCache.get(key);// Read from cache.// ... Do other work in parallel to cache retrieval.try{value=(byte[])futureValue.get();if(value==null){value=BigInteger.valueOf(count).toByteArray();asyncCache.put(key,value);}else{// Increment valuecount=newBigInteger(value).longValue();count++;value=BigInteger.valueOf(count).toByteArray();// Put back in cacheasyncCache.put(key,value);}}catch(InterruptedException|ExecutionExceptione){thrownewServletException("Error when waiting for future value",e);}
Para mais informações sobre a API de nível inferior, consulte o
Javadoc do Memcache.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[[["\u003cp\u003eThis page offers Java code examples for utilizing the low-level Memcache API, which is a high-speed, distributed memory caching system for efficient data access.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code demonstrates both synchronous usage with \u003ccode\u003eMemcacheService\u003c/code\u003e and asynchronous usage with \u003ccode\u003eAsyncMemcacheService\u003c/code\u003e for interacting with the cache.\u003c/p\u003e\n"],["\u003cp\u003eThis legacy bundled API is exclusive to first-generation runtimes within the App Engine standard environment, and migration to newer Java environments like Java 11/17 requires review of the provided migration guide.\u003c/p\u003e\n"],["\u003cp\u003eThe examples show how to get, set and increment values in the cache, demonstrating basic operations using the Memcache API.\u003c/p\u003e\n"]]],[],null,["# Memcache Examples\n\nThis page provides code examples in Java for using the\n[low-level Memcache API](/appengine/docs/legacy/standard/java/memcache#Java_Caching_data_with_the_Low-Level_API). Memcache\nis a high-performance, distributed memory object caching system that provides\nfast access to cached data. To learn more about memcache, read the\n[Memcache Overview](/appengine/docs/legacy/standard/java/memcache).\n| This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Java 11/17 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/java-differences) to learn about your migration options for legacy bundled services.\n\n\u003cbr /\u003e\n\nSynchronous usage\n-----------------\n\nLow-level API example using the synchronous `MemcacheService`: \n\n @SuppressWarnings(\"serial\")\n // With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.\n @WebServlet(name = \"MemcacheSync\", description = \"Memcache: Synchronous\",\n urlPatterns = \"/memcache/sync\")\n public class MemcacheSyncCacheServlet extends HttpServlet {\n\n @Override\n public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,\n ServletException {\n String path = req.getRequestURI();\n if (path.startsWith(\"/favicon.ico\")) {\n return; // ignore the request for favicon.ico\n }\n\n MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();\n syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));\n String key = \"count-sync\";\n byte[] value;\n long count = 1;\n value = (byte[]) syncCache.get(key);\n if (value == null) {\n value = BigInteger.valueOf(count).toByteArray();\n syncCache.put(key, value);\n } else {\n // Increment value\n count = new BigInteger(value).longValue();\n count++;\n value = BigInteger.valueOf(count).toByteArray();\n // Put back in cache\n syncCache.put(key, value);\n }\n\n // Output content\n resp.setContentType(\"text/plain\");\n resp.getWriter().print(\"Value is \" + count + \"\\n\");\n }\n }\n\nAsynchronous usage\n------------------\n\nLow-level API example using `AsyncMemcacheService`: \n\n AsyncMemcacheService asyncCache = MemcacheServiceFactory.getAsyncMemcacheService();\n asyncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));\n String key = \"count-async\";\n byte[] value;\n long count = 1;\n Future\u003cObject\u003e futureValue = asyncCache.get(key); // Read from cache.\n // ... Do other work in parallel to cache retrieval.\n try {\n value = (byte[]) futureValue.get();\n if (value == null) {\n value = BigInteger.valueOf(count).toByteArray();\n asyncCache.put(key, value);\n } else {\n // Increment value\n count = new BigInteger(value).longValue();\n count++;\n value = BigInteger.valueOf(count).toByteArray();\n // Put back in cache\n asyncCache.put(key, value);\n }\n } catch (InterruptedException | ExecutionException e) {\n throw new ServletException(\"Error when waiting for future value\", e);\n }\n\nFor more information on the low-level API, see the\n[Memcache Javadoc](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/memcache/package-summary)."]]