在以前的文章中,咱们已经介绍过了JFinal中Cache的一些简单使用,这篇文章将讲述EhCachePlugin的使用, EhCachePlugin是JFinal集成的缓存插件,经过使用EhCachePlugin能够提升系统的并发访问速度。html
1.导入EhCachePlugin的相关jar包:、java
2.ehcache.xml配置文件数据库
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true"> <!--指定一个文件,当ehcache把数据写到硬盘上时,会默认把数据写到该文件下--> <!--user.home - 用户主目录;user.dir - 用户当前工做目录;java.io.tmpdir - 默认临时文件路径。--> <diskStore path="java.io.tmpdir" /> <!-- 设定缓存的默认数据过时策略 --> <defaultCache maxElementsInMemory="10000" eternal="true" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true"> </defaultCache> <!--自定义cache--> <cache name="user/list" maxElementsInMemory="10000" maxElementsOnDisk="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="900" timeToLiveSeconds="1800" memoryStoreEvictionPolicy="LFU"> </cache> </ehcache>
3.在JFinal的基本配置类中添加EhCachePlugin插件:缓存
@Override public void configPlugin(Plugins me) { DruidPlugin druidPlugin=creatDruidPlugins(); me.add(druidPlugin); ActiveRecordPlugin arp=new ActiveRecordPlugin(druidPlugin); //创建了数据库表到Model的映射 _MappingKit.mapping(arp); me.add(arp); //配置缓存插件 me.add(new EhCachePlugin()); }
CacheKit是缓存操做工具类,可对缓存进行一系列的操做。并发
下面是实例:app
public void text(){ User user = new User().dao(); List<User> users = CacheKit.get("cacheTest","userlist"); if(users == null){ users = user.find("select * from user"); CacheKit.put("cacheTest","userlist",users); } setAttr("userList",users); render("index.html"); }
CacheKit能够对缓存进行读写操做,CacheKit.get()方法中,第一个参数为cache的名称,这个应与ehcache.xml中所配置的name相同,第二个参数为key表示着取值时的对象。在CacheKit.put()向缓存中放数据的方法中,第一个参数为cache的名称,第二个参数为取值时用到的key,第三个参数则为所要放入缓存的对象。ide
除了get()以及put方法以外,CacheKit还有一下操做方法:工具
List getKeys(String cacheName)
:获取名称为“cacheName”的cache中所有key。ui
remove(String cacheName, Object key)
:删除某一缓存。removeAll(String cacheName)
:删除cache中的所有缓存。static Cache getOrAddCache(String cacheName)
:根据cacheName获取或建立cache。
除了使用CacheKit对缓存进行操做以外,JFinal还提供了 CacheInterceptor拦截器,该拦截器能够将action所需数据所有缓存起来,下次请求到来时若是cache存在则直接使用数据并render,而不会去调用action。使用该用法以前须要将ehcache.xml中的cache的name命名为action:spa
如:
@Before(CacheInterceptor.class) public void list() { User user1 = getModel(User.class); UserService userService = new UserService(); userService.add(user1); setAttr("userList", userService.queryUsetrList()); render("index.html"); }
此时,cache的name将为<cache name="/user/list" ...>
若cache的name为自定义的,则可以使用@CacheName(" cachename ") 注解来取代actionkey。
EvictInterceptor能够根据CacheName注解自动清除缓存。
如:
@Before(EvictInterceptor.class) public void update(){ getModel(User.class).update(); render("index.html"); }
EvictInterceptor与CacheInterceptor的配合能够很好地更新缓存的数据。
如下是EvictInterceptor的源码:
咱们能够看到,拦截器被调用后,将调用CacheKit.removeAll()方法将缓存所有清除。
JFinal的缓存机制虽好用,但咱们要注意缓存操做并不适用与不少查询。而对于一些在短时间内数据变更不大而且查询复杂的数据而言,缓存可以很好的发挥其做用。