MemcacheServlet.java
package memcache;赤文字の部分でCache設定の処理です。
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.cache.CacheStatistics;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;
import com.google.appengine.api.memcache.MemcacheService;
@SuppressWarnings("serial")
public class MemcacheServlet extends HttpServlet
{
Cache cache;
@SuppressWarnings("unchecked")
@Override
public void init() throws ServletException
{
// TODO Auto-generated method stub
super.init();
try
{
Map props = new HashMap();
props.put(com.google.appengine.api.memcache.stdimpl.GCacheFactory.EXPIRATION_DELTA, 3600);
props.put(MemcacheService.SetPolicy.SET_ALWAYS, true);
CacheFactory cacheFactory = CacheManager.getInstance()
.getCacheFactory();
cache = cacheFactory.createCache(Collections.emptyMap());
} catch (CacheException e)
{
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
resp.setContentType("text/plain");
resp.setCharacterEncoding("utf-8");
resp.getWriter().println("Hello, world");
for (int i = 1; i < 10; i++)
{
if (cache.containsKey("key" + i))
continue;
cache.put("key" + i, "val" + i);
break;
}
resp.sendRedirect("index.html");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().println("Post");
for (int i = 1; i < 10; i++)
{
if (cache.containsKey("key" + i))
resp.getWriter()
.println("key" + i + "=" + cache.get("key" + i));
}
if (cache.size() == 0)
resp.getWriter().println("Cache is null.");
else
{
CacheStatistics stats = cache.getCacheStatistics();
int hits = stats.getCacheHits();
int misses = stats.getCacheMisses();
resp.getWriter().println("<h3>stats.getCacheHits()=" + hits + "</h3>");
resp.getWriter().println("<h3>stats.getCacheMisses()=" + misses + "</h3>");
}
}
}
0 件のコメント:
コメントを投稿