接上文http://xuliangyong.iteye.com/blog/171240
对于第二种方法现用观察着模式来解决
思路是这样:当点击a文章(id=1234)够10次后 ,通知文章管理器更新点击次数
update article set hit_count = hit_count+10 where id = 1234
这样就减少了访问数据库的次数
代码如下:
- publicclassHitCachedextendsObservable{
- privatestaticfinalintDEFAULT_MAX_HITS=10;
- privateMap<Long,Integer>hits=Collections.synchronizedMap(newHashMap<Long,Integer>());
- /**
- *最大点击量。超过该值就更新数据库
- */
- privateintmaxHits=DEFAULT_MAX_HITS;
- publicHitCached(){}
- publicHitCached(intmaxHits){
- this.maxHits=maxHits;
- }
- publicvoidput(Longkey,Integervalue){
- hits.put(key,value);
- }
- /**
- *为指定key增加指定的点击量
- *@paramhitIncreased增加的点数
- */
- publicvoidaddHit(Longkey,IntegerhitIncreased){
- if(!hits.containsKey(key))
- hits.put(key,0);
- Integervalue=hits.get(key);
- if(value+hitIncreased>=maxHits){
- setChanged();
- notifyObservers(KeyValuePair.create(key,value+hitIncreased));
- hits.remove(key);
- }else{
- hits.put(key,value+hitIncreased);
- }
- }
- publicIntegerget(Longkey){
- returnhits.get(key);
- }
- publicvoidclear(){
- hits.clear();
- }
- }
- publicclassArticleManagerImplextendsHibernateGenericDao<Article,Long>implementsArticleManager,Oberver{
- publicvoidupdate(Observableo,Objectarg){
- KeyValuePairkeyValue=(KeyValuePair)arg;
- Articlearticle=this.get(keyValue.getKey());
- article.setHitCount(article.getHitCount()+keyValue.getValue());
- save(article);
- }
action中调用
- privatestaticHitCachedhitCached=newHitCached(5);
- publicStringview(){
- if(id!=null){
- entity=articleManager.get(id);
- hitCached.addObserver(articleManager);
- hitCached.addHit(id,1);
- }
- }
这样没十次查看才update一次数据库 更新一次缓存 性能得到了大的提升
存在的问题:
停止服务会丢失一些数据 可加一个监听器 来处理