Skip to content

Commit

Permalink
Update memcache with code from appengine documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Shun Fan committed Apr 18, 2016
1 parent f394e51 commit c0a1f15
Showing 1 changed file with 15 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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;
Expand All @@ -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]

0 comments on commit c0a1f15

Please sign in to comment.