CacheService.java

package grp.pt.common.bs;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import grp.pt.common.ICacheService;
import grp.pt.util.PropertyUtil;
import grp.pt.util.cache.CacheKeyConstant;
import grp.pt.util.model.Session;

/**
 * 缓存服务
 * @author scold,hlf
 * @version 2013.09.30.00
 */
@CacheConfig(cacheNames="common-caches")
@Repository
public class CacheService  implements ICacheService{

	private static final Log logger = LogFactory.getLog(CacheService.class);
	
	@Autowired
	private RedisTemplate<Object,Object> rt;
	
	/**
	 *	获取缓存的key
	 *	根据session在key前加标识 
	 */
	private String getCacheKey(Session session, String key) {
		if(session == null) {
			return key;
		}
		String cacheKey = session.getTenantId()+"#"+session.getBusiYear()+"#"+key;
		return cacheKey;
	}

	private String getYearKey(int year, String key){
		return year+key;
	}

	/**
	 * 由session.rgId + session.busiYear + key 构成缓存key
	 * @param session 会话对象
	 * @param key 外部传入的key值
	 * @return 真正的key值
	 */
	private String getRgYearKey(Session session, String key){
		StringBuffer keyStringBuffer = new StringBuffer();
		keyStringBuffer.append(session.getTenantId()).append(session.getBusiYear()).append(key);
		return keyStringBuffer.toString();
	}
	
	/**
	 * 由session.rgId + session.busiYear + key 构成缓存key值获取缓存对象
	 */
	public Object get(Session session, String key) {
		String cacheKey = getCacheKey(session, key);
		return this.getFromCache(cacheKey);
	}
	/**
	 * 从缓存中将key为reakKey的缓存拿出来
	 * @param realKey
	 * @return
	 */
	private Object getFromCache(String realKey){
		return rt.opsForValue().get(realKey);
	}
	
	
	public void put(Session session, String key, Object value) {
		String cacheKey = getCacheKey(session, key);
		this.putToCache(cacheKey, value);	
	}
	/**
	 * 将value存入缓存
	 * @param realKey
	 * @return
	 */
	private Object putToCache(String realKey,Object value){
		rt.opsForValue().set(realKey, value);
		return value;
	}
	
	public boolean remove(Session session, String key) {
		String cacheKey = getCacheKey(session, key);
		return this.removeFromCache(cacheKey);
	}
	/**
	 * 从缓存中移除
	 * @param realKey
	 * @return
	 */
	private boolean removeFromCache(String realKey){
		rt.delete(realKey);
		return true;
	}
	
	/**
	 * @Description:模糊匹配缓存中的key进行缓存清理操作
	 * @param key	该参数需符合redis的key的模糊匹配写法
	 */
	public void removeAll(String key) {
		rt.delete(keys(key));
	}
	
	/**
	 * @Description: 查询所有符合模糊匹配key规则的所有rediskey
	 * @param key 该参数需符合redis的key的模糊匹配写法
	 * @return	符合传入模糊匹配key的所有rediskey
	 */
	public Set<Object> keys(String key) {
		return rt.keys(key);
	}
	
	/**
	 * HashOperations<K, HK, HV>  结构H key : Map<? extends HK, ? extends HV> m
	 */
	/**
	 *	reids的hash操作,根据K和HK(key2)获取HV
	 */
	public Object getMap(Session session, String key, Object key2) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForHash().get(cacheKey, key2);
	}
	
	/**
	 *	reids的hash操作,根据key获取缓存中Map<HK, HV> 
	 */
	public Map getMap(Session session, String key) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForHash().entries(cacheKey);
	}
	
	/**
	 *	reids的hash操作,根据Key获取List<HV>
	 */
	public List<Object> getMapForList(Session session, String key) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForHash().values(cacheKey);
	}
	
	/**
	 *	reids的hash操作,向缓存中保存K:Map数据(覆盖保存)
	 */
	public void putMap(Session session, String key, Map value) {
		String cacheKey = getCacheKey(session, key);
		removeFromCache(cacheKey);
		rt.opsForHash().putAll(cacheKey, value);
	}
	
	/**
	 *	reids的hash操作,向缓存中保存K:Map数据(增量保存)
	 */
	public void putMapToAdd(Session session, String key, Map value) {
		String cacheKey = getCacheKey(session, key);
		rt.opsForHash().putAll(cacheKey, value);
	}
	
	/**
	 *	 reids的hash操作,设置K对应的Map中HK对应的HV的值
	 */
	public void putMap(Session session, String key, Object key2,  Object value) {
		String cacheKey = getCacheKey(session, key);
		rt.opsForHash().put(cacheKey, key2, value);
	}
	
	/**
	 *	reids的hash操作,删除K对应的Map中的HK对应的数据 
	 */
	public Long removeMap(Session session, String key, Object key2) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForHash().delete(cacheKey, key2);
	}
	
	/**
	 * ListOperations<K, V>  redis的list操作
	 */
	/**
	 *	 reids的list操作,在集合尾部插入一个值
	 */
	public void rightPush(Session session, String key,  Object value) {
		String cacheKey = getCacheKey(session, key);
		rt.opsForList().rightPush(cacheKey, value);
	}

	/**
	 * ListOperations<K, V>  redis的list操作
	 */
	/**
	 *	 reids的list操作,在集合尾部插入一个值
	 */
	public void leftPush(Session session, String key,  Object value) {
		String cacheKey = getCacheKey(session, key);
		rt.opsForList().leftPush(cacheKey, value);
	}
	/**
	 *	 reids的list操作,在集合尾部插入多个值
	 */
	public void rightPushAll(Session session, String key, Object ...values) {
		String cacheKey = getCacheKey(session, key);
		rt.opsForList().rightPushAll(cacheKey, values);
	}
	
	/**
	 *	 reids的list操作,在集合中放入一个集合的数据
	 */
	public void rightPushAll(Session session, String key, Object collection) {
		String cacheKey = getCacheKey(session, key);
		rt.opsForList().rightPushAll(cacheKey, collection);
	}
	
	/**
	 *	 reids的list操作,获取集合大小
	 */
	public long listSize(Session session, String key){
		String cacheKey = getCacheKey(session, key);
		return rt.opsForList().size(cacheKey);
	}
	
	/**
	 *	 reids的list操作,从集合头部取出一个值
	 */
	public Object leftPop(Session session, String key) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForList().leftPop(cacheKey);
	}
	
	/**
	 *	 reids的list操作,从集合尾部取出一个值
	 */
	public Object rightPop(Session session, String key) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForList().rightPop(cacheKey);
	}
	
	/**
	 *	 reids的list操作,删除并返回存储的列表中的第一个元素
	 */
	public Object leftPop(Session session,String key, long timeout, TimeUnit unit) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForList().leftPop(cacheKey, timeout, unit);
	}
	
	
	/**
	 *	 reids的set集合操作,在有序不可重复集合中添加值
	 */
	public Long setAdd(Session session,String key,Object ...values) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForSet().add(cacheKey, values);
	}
	
	/**
	 *	 reids的set集合操作,判断集合中是否有指定值
	 */
	public Boolean isSetMember(Session session,String key,Object value) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForSet().isMember(cacheKey, value);
	}
	
	/**
	 *	 reids的set集合操作,集合数据查询
	 */
	public Set<Object> setMembers(Session session,String key) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForSet().members(cacheKey);
	}
	
	
	/**
	 * 是否存在Key
	 */
	public boolean keyExists(Session session, String key) {
		String cacheKey = getCacheKey(session, key);
		try {
			return rt.hasKey(cacheKey);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * Key类型查询
	 */
	public String keyType(String key) {
		DataType type = rt.type(key);
		return type.code();
	}
	
	/**
	 * 指定缓存失效时间
	 * @param key 键
	 * @param time 时间(秒)
	 * @return
	 */
	public boolean expire(String key,long time){
		try {
			if(time>0){
				rt.expire(key, time, TimeUnit.SECONDS);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 根据key 获取过期时间
	 * @param key键 不能为null
	 * @return 时间(秒) 返回0代表为永久有效
	 */
	public long getExpire(String key){
		return rt.getExpire(key,TimeUnit.SECONDS);
	}
	
	/**
	 * 以无区划的的形式获取缓存中
	 * @param session
	 * @param key
	 * @return
	 */
	public Object getNoRg(int year, String key) {
		return this.getFromCache(getYearKey(year, key));
	}
	
	/**
	 * 以无区划的形式存入缓存服务器,key中会添加rg信息
	 * @param session
	 * @param key
	 * @param value
	 */
	public void putNoRg(int year, String key, Object value) {
		this.putToCache(getYearKey(year, key), value);
	}
	
	/**
	 * 移除缓存中的数据(无区划形式)
	 * @param session
	 * @param cacheType
	 * @param key
	 * @return
	 */
	public boolean removeNoRg(int year, String key) {
		return this.removeFromCache(getYearKey(year, key));
	}
	
	/**
	 * 批量缓存对象的快捷方法,会将对象以key值前缀+对象指定的属性值形成真正的key进行缓存各个对象,
	 * 并将对象的指定属性形成List并进行缓存
	 * @param objectsToCache 所有的数据
	 * @param keyPrefix 缓存前缀
	 * @param identityPropertyName 对象唯一标识对象的字段
	 * @return 根据identityPropertyName参数取出的值形成的List
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List saveToCache(Session se, List objectsToCache, String keyPrefix, String identityPropertyName){
		List list=new ArrayList();
		for(Object o : objectsToCache){
			Object id=PropertyUtil.getPropertySmart(o, identityPropertyName);
			list.add(id);
			this.put(se, keyPrefix+id, o);
		}
		//将存储id值 的List存到缓存中
		this.put(se, keyPrefix+CacheKeyConstant.LIST, list);
		return list;
	}
	
	/**
	 * 从缓存中拿到带有Id List
	 * @param keyPrefix
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Object> getIdList(Session se, String keyPrefix){
		return (List)this.get(se, keyPrefix+CacheKeyConstant.LIST);
	}
	
	/**
	 * 从缓存中set带有Id List
	 * @param keyPrefix
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public void setIdList(Session se, String keyPrefix,List list){
		this.put(se, keyPrefix+CacheKeyConstant.LIST,list);
	}
	
	/**
	 * 从缓存中拿到关于front_key的所有Object对象
	 * @param keyPrefix 缓存id前半部分(由CacheKeyConstant内的常量拼成)
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List getObjectList(Session se, String keyPrefix){
		List<Object> list = new ArrayList<Object>();
		List<Object> idlist = this.getIdList(se, keyPrefix);
		for(int i=0; i < idlist.size(); i++){
			Object id=idlist.get(i);
			list.add(this.get(se, keyPrefix+id));
		}
		return list;
	}

	@Override
	public Boolean setRemove(Session session, String key, Object... values) {
		String cacheKey = getCacheKey(session, key);
		if(!keyExists(session, key)) {
			return true;
		}
		if(values == null || values.length <= 0) {
			return remove(session, key);
		}
		return rt.opsForSet().remove(cacheKey, values) > 0;
	}

	@Override
	public List<Object> getListrange(Session session, String key, long start, long end) {
		String cacheKey = getCacheKey(session, key);
		return rt.opsForList().range(cacheKey, start, end);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值