Memcache 示例

本页面介绍以 Java 编写的使用低层级 Memcache API 的代码示例。Memcache 是一个高性能的分布式内存对象缓存系统,可让您快速访问缓存数据。如需详细了解 Memcache,请参阅 Memcache 概览

同步使用

下面是使用同步 MemcacheService 的低层级 API 示例:

@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");
  }
}

异步使用

下面是使用 AsyncMemcacheService 的低层级 API 示例:

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);
}

如需详细了解低层级 API,请参阅 Memcache Javadoc