我是一名新手Android开发人员。我正在尝试构建基于应用程序引擎的应用程序。我现在可以继续工作,但我意识到我需要使用memcache来优化数据库访问。但我很难理解一些基本概念。所以我的问题如下:
我在一本书上得到了这个例子但它使用了很多HTTP引用。这种类型的示例是否也适用于Android应用程序,还是仅用于网站的使用?。
public class ETagCacheServlet extends HttpServlet {
private static final long serialVersionUID = 4308584640538822293L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
MemcacheService cache = MemcacheServiceFactory
.getMemcacheService();
String cacheKey = request.getRequestURI() + "." + "etag";
String result;
if (!cache.contains(cacheKey) ||
!cache.get(cacheKey).equals(request
.getHeader("If-None-Match"))) {
String etag = Long.toString(System.currentTimeMillis());
response.setHeader("ETag", etag);
cache.put(cacheKey, etag);
result = "Loaded into cache at " + (new Date());
response.getWriter().write(result);
} else {
response.setStatus(304);
}
}
}
您是否知道任何有工作样本应用程序的来源?
也许你笑着读这些问题,但我真的无法解决这些问题。提前谢谢。
编辑:我试图将memcache添加到我的代码失败,请问您能看一下代码吗?
@SuppressWarnings({ "unchecked", "unused" })
@ApiMethod(name = "queryDesire")
public CollectionResponse<Desire> queryDesire(
@Nullable @Named("cursor") String cursorString,
@Nullable @Named("limit") Integer limit,
@Nullable @Named("first") Integer first,
@Nullable @Named("name") String name){
EntityManager mgr = null;
Cursor cursor = null;
List<Desire> execute = null;
try {
String keyDesire = "mem_" + name;
List<Desire> memDesire = (List<Desire>) memcache.get(keyDesire);
if (memDesire == null) {
mgr = getEntityManager();
Query query2 = mgr.createQuery("select i from Desire i where i.ctgry = :name ");
if (cursorString != null && cursorString != "") {
cursor = Cursor.fromWebSafeString(cursorString);
query2.setHint(JPACursorHelper.CURSOR_HINT, cursor);
}
if (limit != null) {
query2.setFirstResult(first);
query2.setMaxResults(limit);
}
execute = (List<Desire>) query2.setParameter("name", name).getResultList();
cursor = JPACursorHelper.getCursor(execute);
if (cursor != null)
cursorString = cursor.toWebSafeString();
for (Desire obj : execute)
;
CollectionResponse.<Desire> builder().setItems(execute)
.setNextPageToken(cursorString).build();
memcache.put("mem_cache", queryDesire);
}
return CollectionResponse.<Desire> builder().setItems(execute)
.setNextPageToken(cursorString).build();
}
finally {
mgr.close();
}
}
答案 0 :(得分:1)
Memcache用于服务器端,即App Engine。它通常用于加速从服务器到客户端的响应,但它与客户端代码无关。换句话说,如果您在App Engine端使用Memcache,则客户端无需进行任何更改。
是的,您可以使用Memcache的低级API。
请参阅问题1的回答。无论 应用如何与服务器通信,都可以使用Memcache。
Memcache以多种不同的方式使用,因此您可能需要发布一个特定的问题,我们也许可以提供帮助。同时,这是我的代码中的一个例子。我的应用经常需要时区,它们永远不会改变。因此,使用Memcache加速响应是有意义的。
private static final MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
public static ArrayList<String> getTimeZones() {
ArrayList<String> timeZones = (ArrayList<String>) memcache.get("time_zones");
if (timeZones == null) {
// This method reads time zones from a properties file
timeZones = prepareTimeZones();
memcache.put("time_zones", timeZones);
}
return timeZones;
}