play framework2开发(八)

The Play cache API

缓存数据在应用开发中是可选择的,Play提供一个全局。缓存重要一点是你存储的数据会消失。

对于任何存储在缓存中的数据,获取时如果发现不存在则需要再次存储进缓存。Play会一直保存数据直到生命周期结束。

Cache.set("data1", userForm);

/ Cache for 15 minutes

Cache.set("item.key", frontPageNews, 60 * 15);

News news = Cache.get("data1");

Cache.remove("data1");


缓存 HTTP responses

@Cached("homePage")
public static Result index() {
  return ok("Hello world");
}

缓存 in templates

You may also access the cache from a view template.

@cache.Cache.getOrElse("cached-content", 3600) {
    
    
     <div>Im cached for an hour</div>
}


会话缓存

Play提供一个全局缓存,数据对于任何人都是可见的。怎样才能限制只给特定的用户可见呢?下边这个例子:

// Generate a unique ID
String uuid=session("uuid");
if(uuid==null) {
	uuid=java.util.UUID.randomUUID().toString();
	session("uuid", uuid);
}

// Access the cache
News userNews = Cache.get(uuid+"item.key");
if(userNews==null) {
	userNews = generateNews(uuid);
	Cache.set(uuid+"item.key", userNews );
}



猜你喜欢

转载自blog.csdn.net/penkee/article/details/8755507
今日推荐