java缓存用例(包含读写锁,单例)

</pre><pre name="code" class="java">

一个完整的使用缓存的案例
一、缓存对象类

package com.lendingcloud.rms.web.CacheUtil;

import java.util.List;
import java.util.Map;
/**
 * 
 * 看板数据的缓存对象
 * @author shenrongrong
 *
 */
public class CacheBean<?> {
	// 缓存ID
	private String key;
	// 缓存数据类型 List<?>
	private List<?> list;
	// 缓存数据类型 List<Map<String, String>>
	private List<Map<String, String>> listMap;
	// 缓存数据类型 List<List<Map<String, String>>>
	private List<List<Map<String, String>>> listListMap;
	// 缓存数据类型 map
	Map<String, Object> map;
	// 更新时间
	private long timeOut;
	// 是否终止
	private boolean expired;

	public CacheBean() {
		super();
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public List<?> getList() {
		return list;
	}

	public void setList(List<?> list) {
		this.list = list;
	}

	public List<Map<String, String>> getListMap() {
		return listMap;
	}

	public void setListMap(List<Map<String, String>> listMap) {
		this.listMap = listMap;
	}

	public List<List<Map<String, String>>> getListListMap() {
		return listListMap;
	}

	public void setListListMap(List<List<Map<String, String>>> listListMap) {
		this.listListMap = listListMap;
	}

	public long getTimeOut() {
		return timeOut;
	}

	public void setTimeOut(long timeOut) {
		this.timeOut = timeOut;
	}

	public boolean isExpired() {
		return expired;
	}

	public void setExpired(boolean expired) {
		this.expired = expired;
	}

	public Map<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}
	

}

二、缓存的变量名,常量化

package com.lendingcloud.rms.web.CacheUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 
 * 看板数据的缓存变量名
 * @author shenrongrong
 *
 */
public class CacheName {
	 /**
     * 仪表盘
     * @return
     */
	/* 总 */
	public final static String ALL = "ALL";
	/* 南京分公司 */
	public final static String NANJING = "nanjing";
	/* 无锡分公司 */
	public final static String WUXI = "wuxi";
	/* 苏州分公司 */
	public final static String SUZHOU = "suzhou";
	/* 山东分公司 */
	public final static String SHANDONG = "shandong";
	/* 滁州分公司 */
	public final static String CHUZHOU = "chuzhou";
	/* 泰州分公司 */
	public final static String TAIZHOU = "taizhou";
	/* 常州分公司 */
	public final static String CHANGZHOU = "changzhou";
	/* 途牛 */
	public final static String TUNIU = "tuniu";
	/* 查询当月业务量 */
	public final static String QUERYBUSINESSVOLUMELIST_MONTH = "queryBusinessVolumeList_month";
	/* 查询当天业务量 */
	public final static String QUERYBUSINESSVOLUMELIST_DAY = "queryBusinessVolumeList_day";
	
	 /**
     * 活跃度
     * @return
     */
	/* 投资活跃度图表 */
	public final static String QUERYINVESTMENTACTIVITYLIST = "queryInvestmentActivityList";
	
	 /**
     * 地图
     * @return
     */
	/*投资城市排名数据 */
	public final static String CITYRANKINGDATA = "cityRankingData";
	/*按省份统计投资数据 */
	public final static String PROVINCEALLSTDATA = "provinceAllStData";
	/*按城市统计投资数据 */
	public final static String CITYALLSTDATA = "cityAllStData";
	/*实时统计投资数据--第一次请求 */
	public final static String INVESTHISDATA_FIRST = "investHisData_first";
	/*实时统计投资数据--间隔请求 */
	public final static String INVESTHISDATA_INTERVAL = "investHisData_interval";
	
	/**
	 * 投资折线图
	 * @return
	 */
	/*查询当天投资人列表信息 */
	public final static String QUERYINVESTLISTINTHISDATEPER = "queryInvestListInThisDatePer";
	/*查询投资列表 */
	public final static String QUERYINVESTBIZSTATSLIST_INVESTLIST = "queryInvestBizStatsList_InvestList";
	/*查询投资列表_以时间为轴_以半小时为间隔 */
	public final static String QUERYINVESTBIZSTATSLIST_INTHISDATEALL_EVERYHALFHOUR = "queryInvestBizStatsList_InThisDateAll_everyHalfHour";
	

	public static String getCacheName(String param) {
		if (param.equals(CacheName.ALL)) {
			return CacheName.ALL;
		} else if (param.equals(CacheName.NANJING)) {
			return CacheName.NANJING;
		} else if (param.equals(CacheName.WUXI)) {
			return CacheName.WUXI;
		} else if (param.equals(CacheName.SUZHOU)) {
			return CacheName.SUZHOU;
		} else if (param.equals(CacheName.SHANDONG)) {
			return CacheName.SHANDONG;
		} else if (param.equals(CacheName.CHUZHOU)) {
			return CacheName.CHUZHOU;
		} else if (param.equals(CacheName.TAIZHOU)) {
			return CacheName.TAIZHOU;
		} else if (param.equals(CacheName.CHANGZHOU)) {
			return CacheName.CHANGZHOU;
		} else if (param.equals(CacheName.TUNIU)) {
			return CacheName.TUNIU;
		}
		return "";
	}
	
	//获取当前整点的时间(min分钟间隔)
	public static Long  getCurrentTime(Date time,Long min){
		Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH)+1;//获取月份
        int day=cal.get(Calendar.DATE);//获取日
        int hour=cal.get(Calendar.HOUR);//小时
        int minute=cal.get(Calendar.MINUTE);//分           
        String stringTime =year+"-"+month+"-"+day+" "+hour+":"+(minute-minute%(min/(60*1000)))+":"+0;
      //  System.out.println(stringTime);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
         date = format.parse(stringTime);
        } catch (ParseException e) {
         e.printStackTrace();
        }
        return date.getTime();
	}
	public static void main(String[] args){  
		System.out.println("queryInvestListInThisDatePer".toUpperCase()); 
		System.out.println("queryInvestBizStatsList_InvestList".toUpperCase()); 
		System.out.println("queryInvestBizStatsList_InThisDateAll_everyHalfHour".toUpperCase()); 
	    Long stt=	CacheName.getCurrentTime(new Date(),300000L);
	    System.out.println(stt);
	 }
} 

三、缓存类

package com.lendingcloud.rms.web.CacheUtil;

import java.util.HashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 
 * 看板数据的缓存
 * @author shenrongrong
 *
 */
public class CacheUtil{
	
	 	private static CacheUtil cacheUtil;
	 	private HashMap<String, CacheBean<?>> mapCache ;

		//读写锁
	    private ReadWriteLock rwlock;
	    private CacheUtil(){
	    	rwlock = new ReentrantReadWriteLock();
	    	mapCache = new HashMap<String, CacheBean<?>>();
	    }
	    
	    /**
	     * 双重校验锁单例
	     * @return
	     */
	    public static CacheUtil getInstance(){
	        if(cacheUtil == null){
	        	synchronized(CacheUtil.class){
	        		if(cacheUtil == null){
	        			cacheUtil = new CacheUtil();
	        		}
	        	}
	        }
	        return cacheUtil;
	    }
	    /**
	     * 删除缓存
	     * @param 
	     */
	    public void removeCache(String key){
	    	this.rwlock.writeLock().lock();
	    	try{
	    		mapCache.remove(key);
	    	}finally{
	    		this.rwlock.writeLock().unlock();
	    	}
	    }
	    /**
	     * 载入缓存
	     * @param 
	     */
	    public void addCache(String keyStr, CacheBean<?> obj){
	    	this.rwlock.writeLock().lock();
	    	try{
		    	if(this.mapCache.containsKey(keyStr)){
		    		return;
		    	}
		    	else{
		    		this.mapCache.put(keyStr, obj);
		    	}
	    	}finally{
	    		this.rwlock.writeLock().unlock();
	    	}
	    }
	    
	    /**
	     * 获取当前缓存数据
	     * @param 
	     * @return
	     */
	    public synchronized CacheBean<?> getCache(String keyStr,long currentTime,long min){
	    	//读锁,防止正在读的时候另外一个线程做了删除操作
	    	boolean isUnlock = false;
	    	this.rwlock.readLock().lock();
	    	try{
	    		if(this.mapCache.containsKey(keyStr)){
	    			CacheBean<?> cache=this.mapCache.get(keyStr);
	    			if(checkTF(cache,currentTime,min)){
	    				return cache;
	    			}else{
	    				this.rwlock.readLock().unlock();
	    				isUnlock = true;
	    				removeCache(keyStr);
	    				return null;
	    			}
	    		}else{
	    			return null;
	    		}
	    	}finally{
	    		if(!isUnlock){
		    		this.rwlock.readLock().unlock();
	    		}
	    	}
			
	    }
	    
	    /**
	     * 判断缓存是否终止
	     * @param 
	     * @return
	     */
		public static boolean checkTF(CacheBean<?> cache,long currentTime,long min) {
			if (null == cache) { 
				return false;
			}
			long nowDt = currentTime; // 当前的毫秒数
			long cacheDt = cache.getTimeOut(); // 缓存内的过期毫秒数
			long betwweenmin = min; // 更新时间间隔
			if (cacheDt <= 0 || cacheDt < nowDt-betwweenmin) { 
				return false;
			} else { 
				return true;
			}
		}
}

四、调用缓存的一个案例缓存类

package com.lendingcloud.rms.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.lendingcloud.rms.domain.InvestACTStats;
import com.lendingcloud.rms.service.InvestACTStatsService;
import com.lendingcloud.rms.util.Constants;
import com.lendingcloud.rms.web.CacheUtil.CacheBean;
import com.lendingcloud.rms.web.CacheUtil.CacheName;
import com.lendingcloud.rms.web.CacheUtil.CacheUtil;

@Controller
@RequestMapping("/investACTStats")
@SessionAttributes("currentUser")
public class InvestACTStatsController {
	@Resource
	private InvestACTStatsService service;
	/**
	 * 投资活跃度图表
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = {"/queryInvestmentActivityList" }, method = RequestMethod.POST)
	@ResponseBody
	public Object queryInvestmentActivityList(HttpServletRequest request,HttpSession session){
		CacheUtil cacheUtil = CacheUtil.getInstance();
		Map<String, Object> map = new HashMap<String, Object>();
		Long min = Long.valueOf(request.getParameter("timeInterval"));
		Long currentTime = CacheName.getCurrentTime(new Date(),min);
		 //第一次访问的数据
		CacheBean<?>	cacheBean =  cacheUtil.getCache(CacheName.QUERYINVESTMENTACTIVITYLIST, currentTime, min);
		//如果第一次访问,且缓存中存在间隔内访问的数据,则从缓存中获取
		if(cacheBean != null&&cacheBean.getMap()!=null)
		{
			Map<String, Object> resultCache=cacheBean.getMap();
			//System.out.println(new Date(currentTime)+CacheName.QUERYINVESTMENTACTIVITYLIST+"(投资活跃度图表):从缓存获取访问数据。。。"+resultCache.size()+"条");
			return resultCache;
		}else
		{
		List<InvestACTStats> investACTStatsList_nanjing = new ArrayList<InvestACTStats>();
		List<InvestACTStats> investACTStatsList_wuxi = new ArrayList<InvestACTStats>();
		List<InvestACTStats> investACTStatsList_suzhou = new ArrayList<InvestACTStats>();
		List<InvestACTStats> investACTStatsList_shandong = new ArrayList<InvestACTStats>();
		List<InvestACTStats> investACTStatsList_chuzhou = new ArrayList<InvestACTStats>();
		List<InvestACTStats> investACTStatsList_taizhou = new ArrayList<InvestACTStats>();
		List<InvestACTStats> investACTStatsList_changzhou = new ArrayList<InvestACTStats>();
		//投资活跃度-南京
		investACTStatsList_nanjing = service.queryInvestmentActivityList(Constants.NANJING);
		//投资活跃度-无锡
		investACTStatsList_wuxi = service.queryInvestmentActivityList(Constants.WUXI);
		//投资活跃度-苏州
		investACTStatsList_suzhou = service.queryInvestmentActivityList(Constants.SUZHOU);
		//投资活跃度-山东
		investACTStatsList_shandong = service.queryInvestmentActivityList(Constants.SHANDONG);
		//投资活跃度-滁州
		investACTStatsList_chuzhou = service.queryInvestmentActivityList(Constants.CHUZHOU);
		//投资活跃度-泰州
		investACTStatsList_taizhou = service.queryInvestmentActivityList(Constants.TAIZHOU);
		//投资活跃度-常州
		investACTStatsList_changzhou = service.queryInvestmentActivityList(Constants.CHANGZHOU);
		map.put("investACTStatsList_nanjing", investACTStatsList_nanjing);
		map.put("investACTStatsList_wuxi", investACTStatsList_wuxi);
		map.put("investACTStatsList_suzhou", investACTStatsList_suzhou);
		map.put("investACTStatsList_shandong", investACTStatsList_shandong);
		map.put("investACTStatsList_chuzhou", investACTStatsList_chuzhou);
		map.put("investACTStatsList_taizhou", investACTStatsList_taizhou);
		map.put("investACTStatsList_changzhou", investACTStatsList_changzhou);
		map.put("success", true);
		map.put("requestDate", new Date(currentTime));
		//System.out.println(new Date()+CacheName.QUERYINVESTMENTACTIVITYLIST+"(投资活跃度图表):从数据库获取访问数据。。。"+map.size()+"条");
		CacheBean<?> newCacheBean=new CacheBean();
		newCacheBean.setKey(CacheName.QUERYINVESTMENTACTIVITYLIST);
		newCacheBean.setTimeOut(currentTime);
		newCacheBean.setMap(map);
		cacheUtil.addCache(CacheName.QUERYINVESTMENTACTIVITYLIST, newCacheBean);
		//System.out.println(new Date()+CacheName.QUERYINVESTMENTACTIVITYLIST+"(投资活跃度图表):更新缓存数据数据。。。"+map.size()+"条");
		}
		return map;
	}
}

    原文作者:java锁
    原文地址: https://blog.csdn.net/u010251897/article/details/46453119
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞