用观察者模式解决点击一次文章 update一次数据库的问题

对于第二种方法现用观察着模式来解决

思路是这样:当点击a文章(id=1234)够10次后 ,通知文章管理器更新点击次数

update article set hit_count = hit_count+10 where id = 1234

这样就减少了访问数据库的次数

代码如下:

public class HitCached extends Observable{
	private static final int DEFAULT_MAX_HITS = 10;
	private Map<Long, Integer> hits = Collections.synchronizedMap(new HashMap<Long, Integer>());
	
	/**
	 * 最大点击量。超过该值就更新数据库
	 */
	private int maxHits = DEFAULT_MAX_HITS;
	
	public HitCached(){}
	
	public HitCached(int maxHits){
		this.maxHits = maxHits;
	}
	
	public void put(Long key, Integer value){
		hits.put(key, value);
	}
	
	/**
	 * 为指定key 增加指定的点击量
	 * @param hitIncreased 增加的点数 
	 */
	public void addHit(Long key, Integer hitIncreased){
		if( !hits.containsKey(key) )
				hits.put(key, 0);
		Integer value = hits.get(key);
		if(value + hitIncreased >= maxHits){
			setChanged();
			notifyObservers(KeyValuePair.create(key, value + hitIncreased));
			hits.remove(key);
		}else{
			hits.put(key, value + hitIncreased);
		}
		
	}
	
	public Integer get(Long key){
		return hits.get(key);
	}
	
	public void clear(){
		hits.clear();
	}
	
}
 
public class ArticleManagerImpl extends HibernateGenericDao<Article, Long> implements ArticleManager ,Oberver{
	
	public void update(Observable o, Object arg){
		KeyValuePair keyValue = (KeyValuePair)arg;
		Article article = this.get(keyValue.getKey());
		article.setHitCount(article.getHitCount() + keyValue.getValue());
		save(article);
	}
 

action中调用

private static HitCached hitCached = new HitCached(5);

public String view() {
		if (id != null){
			entity = articleManager.get(id);
			hitCached.addObserver(articleManager);
			hitCached.addHit(id, 1);
		}
}

 这样没十次查看才update一次数据库 更新一次缓存 性能得到了大的提升

存在的问题:

停止服务会丢失一些数据 可加一个监听器 来处理

相关推荐