# 7.5 CacheKit
CacheKit
is a utility class for cache operations. Here's a sample code snippet:
public void list() {
List<Blog> blogList = CacheKit.get("blog", "blogList");
if (blogList == null) {
blogList = Blog.dao.find("select * from blog");
CacheKit.put("blog", "blogList", blogList);
}
setAttr("blogList", blogList);
render("blog.html");
}
2
3
4
5
6
7
8
9
The two most important methods in CacheKit
are get(String cacheName, Object key)
and put(String cacheName, Object key, Object value)
. The get
method retrieves data from the cache, while the put
method stores data in the cache. The cacheName
parameter corresponds to the name
attribute value in <cache name="blog" …>
in ehcache.xml
; the key
parameter specifies the key used for retrieval; the value
parameter specifies the data to be cached.
Below is an example of using the overloaded CacheKit.get(String, String, IDataLoader)
method:
public void list() {
List<Blog> blogList = CacheKit.get("blog", "blogList", new IDataLoader(){
public Object load() {
return Blog.dao.find("select * from blog");
}});
setAttr("blogList", blogList);
render("blog.html");
}
2
3
4
5
6
7
8
The CacheKit.get
method provides an IDataLoader
interface, whose load()
method will only be called when the cache value does not exist. The specific operation flow of this method is as follows: First, it tries to retrieve data from the cache using cacheName=blog
and key=blogList
as parameters. If the data exists in the cache, it is returned directly. If it doesn't exist, the IDataLoader.load()
method is called to fetch the data.