# 5.8 Cache caching
# 1. Using Ehcache
ActiveRecord can use caching to greatly improve performance. The default caching implementation is Ehcache. To use it, you need to import the Ehcache JAR package and its configuration file. The following code is an example of using Cache:
public void list() {
List<Blog> blogList = Blog.dao.findByCache("cacheName", "key", "select * from blog");
setAttr("blogList", blogList).render("list.html");
}
2
3
4
In the above example, the cacheName
in the findByCache
method needs to be configured in ehcache.xml
like: <cache name="cacheName" …>
. Additionally, Model.paginateByCache(…)
, Db.findByCache(…)
, and Db.paginateByCache(…)
methods also support caching. To use it, just pass in cacheName
, key
, and configure the corresponding cacheName
in ehcache.xml
.
# 2. Using Any Caching Implementation
Apart from using the default Ehcache implementation, you can also switch to any other caching implementation by implementing the ICache
interface. Below is a simple indicative code implementation:
public class MyCache implements ICache {
public <T>T get(String cacheName, Object key) {
}
public void put(String cacheName, Object key, Object value) {
}
public void remove(String cacheName, Object key) {
}
public void removeAll(String cacheName) {
}
}
2
3
4
5
6
7
8
9
10
11
12
13
As shown in the above code, MyCache
needs to implement the four abstract methods in ICache
. Then you can switch to your own cache implementation with the following configuration:
ActiveRecordPlugin arp = new ActiveRecordPlugin(...);
arp.setCache(new MyCache());
2
In the above code, you can switch the cache implementation by calling ActiveRecordPlugin.setCache(...)
.