so need store information , reload db every 1 hour. looked around , found googles guava cacheloader or ehcache best , simple solution.
i searched google past 4 hours , didn't find anyhting me, real newbie, first time need cache something. please me out.
follwoing issue:
i have entity called news obisouly store news , load them depending on availibilty. im @viewscoped bean. however, dont need load news every time page loaded, news won't modified freqeuntly. why want store news(list < news>) in cache , load them respectively. cache should refreshed every 1 hour.
please me regarding bean, cache listener etc. have no clue how reload data, have use bean etc.
this @viewscoped newscontroller:
@viewscoped public class newscontroller extends basecontroller implements serializable { private static final long serialversionuid = 1l; @persistencecontext protected entitymanager em; private list<news> newslist; @postconstruct public void init() { getavailablenews(); } public void getavailablenews() { if (newslist == null) { info("#############load news db!##########"); newslist = new linkedlist<news>(); @suppresswarnings("unchecked") list<news> result = (list<news>) em.createnativequery( "select * news sysdate between , to+1", news.class).getresultlist(); (news n : result) { newslist.add(n); } } } public void reload(){ newslist = null; getavailablenews(); } public list<news> getnewslist() { return newslist; } public void setnewslist(list<news> newslist) { this.newslist = newslist; }
}
have looked @ ehcache spring annotations (http://ehcache.org/documentation/recipes/spring-annotations)? seems that's need here...
simply add @cacheable(name="getavailablenews") above getavailablenews() method, , framework automatically take care of caching results (first time calls db, fetches results back, , cache them...next time, cache directly)
for work though, need change bit class construct...i remove "newslist" instance variable...that's cause inconsistencies , troubles...(you did build sort of home grown "caching" can understand) , update getavailablenews() method return list object...
@cacheable(name="getavailablenews") public list<news> getavailablenews() { info("#############load news db!##########"); return (list<news>) em.createnativequery( "select * news sysdate between , to+1", news.class).getresultlist(); }
finally, ehcache, can set time expirations on cached entries...hence case, might easy setting timetolive value 1 hour news items...after 1 hour, call db made again...and you'll fetch new "news" values...
Comments
Post a Comment