From c0a1f15eb57f26a86f452657849551e56ab676f2 Mon Sep 17 00:00:00 2001 From: Shun Fan Date: Mon, 18 Apr 2016 15:35:25 -0700 Subject: [PATCH] Update memcache with code from appengine documentation --- .../appengine/memcache/MemcacheServlet.java | 35 ++++++++----------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/appengine/memcache/src/main/java/com/example/appengine/memcache/MemcacheServlet.java b/appengine/memcache/src/main/java/com/example/appengine/memcache/MemcacheServlet.java index 0d817e25af8..1f18110ae8b 100644 --- a/appengine/memcache/src/main/java/com/example/appengine/memcache/MemcacheServlet.java +++ b/appengine/memcache/src/main/java/com/example/appengine/memcache/MemcacheServlet.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Google Inc. All Rights Reserved. + * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import com.google.appengine.api.memcache.MemcacheServiceFactory; import java.io.IOException; -import java.math.BigInteger; import java.util.logging.Level; import javax.servlet.ServletException; @@ -36,27 +35,23 @@ public class MemcacheServlet 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"; - 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"); + byte[] whoKey = "who".getBytes(); + byte[] countKey = "count".getBytes(); + + byte[] who = (byte[]) syncCache.get(whoKey); + String whoString = who == null ? "nobody" : new String(who); + resp.getWriter().print("Previously incremented by " + whoString + "\n"); + syncCache.put(whoKey, "Java".getBytes()); + Long count = syncCache.increment(countKey, 1L, 0L); + resp.getWriter().print("Count incremented by Java = " + count + "\n"); } } // [END example]