Aviso: nos próximos meses, vamos reorganizar o site de documentação do App Engine para facilitar a localização de conteúdo e o alinhamento com o restante dos produtos do Google Cloud. O mesmo conteúdo estará disponível, mas a navegação agora corresponderá ao restante dos produtos do Cloud.
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")
public class MemcacheSyncCacheServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
ServletException {
String path = req.getRequestURI();
if (path.startsWith("/favicon.ico")) {
return; // ignore the request for favicon.ico
}
MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
String key = "count-sync";
byte[] value;
long count = 1;
value = (byte[]) syncCache.get(key);
if (value == null) {
value = BigInteger.valueOf(count).toByteArray();
syncCache.put(key, value);
} else {
// Increment value
count = new BigInteger(value).longValue();
count++;
value = BigInteger.valueOf(count).toByteArray();
// Put back in cache
syncCache.put(key, value);
}
// Output content
resp.setContentType("text/plain");
resp.getWriter().print("Value is " + count + "\n");
}
}
Uso assíncrono
Exemplo de API de nível inferior usando AsyncMemcacheService:
AsyncMemcacheService asyncCache = MemcacheServiceFactory.getAsyncMemcacheService();
asyncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
String key = "count-async";
byte[] value;
long count = 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 value
count = new BigInteger(value).longValue();
count++;
value = BigInteger.valueOf(count).toByteArray();
// Put back in cache
asyncCache.put(key, value);
}
} catch (InterruptedException | ExecutionException e) {
throw new ServletException("Error when waiting for future value", e);
}
Para mais informações sobre a API de nível inferior, consulte o
Javadoc do Memcache.