spring redis

1.pom.xml

  <!-- spring-data -->
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-redis</artifactId>
                <version>${spring-data.version}</version>
            </dependency>

2.redis.properties

#IP\u5730\u5740
redis.pool.host=192.168.7.153
#\u7aef\u53e3\u53f7
redis.pool.port=6379
#redis.pool.pass=
#\u6700\u5927\u5206\u914d\u7684\u5bf9\u8c61\u6570
redis.pool.maxTotal=600
#\u6700\u5927\u80fd\u591f\u4fdd\u6301idel\u72b6\u6001\u7684\u5bf9\u8c61\u6570
redis.pool.maxIdle=300

#\u591a\u957f\u65f6\u95f4\u68c0\u67e5\u4e00\u6b21\u8fde\u63a5\u6c60\u4e2d\u7a7a\u95f2\u7684\u8fde\u63a5
redis.pool.timeBetweenEvictionRunsMillis=30000
#\u7a7a\u95f2\u8fde\u63a5\u591a\u957f\u65f6\u95f4\u540e\u4f1a\u88ab\u6536\u56de
redis.pool.minEvictableIdleTimeMillis=30000
#\u5f53\u8c03\u7528borrow Object\u65b9\u6cd5\u65f6\uff0c\u662f\u5426\u8fdb\u884c\u6709\u6548\u6027\u68c0\u67e5
redis.pool.testOnBorrow=true
#redis\u5f00\u542f\u5f00\u5173,true\u5f00\u542f\uff0cfalse\u4e0d\u5f00\u542f
redis.switch=true
#redis\u9ed8\u8ba4\u7f13\u5b58\u8fc7\u671f\u5929\u6570\uff0c\u5355\u4f4d\u5929
redis.timeout.day=1
#redis\u9ed8\u8ba4\u7f13\u5b58\u8fc7\u671f\u65f6\u95f4\uff0c\u65f6\u5206\u79d2
redis.timeout.time=03:00:00

3.applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Redis缓存配置 -->
    <bean id="redisTemplate"
          class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="jedisConnFactory"/>
    </bean>

    <bean id="jedisConnFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.pool.host}"/>
        <property name="port" value="${redis.pool.port}"/>
        <property name="poolConfig" ref="jedisPoolConfig"/>
    </bean>

    <bean id="jedisPoolConfig"
          class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.pool.maxTotal}"/>
        <property name="maxIdle" value="${redis.pool.maxIdle}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"/>
        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
    </bean>

    <bean id="redisCommons" class="com.common.redis.RedisCommons">
        <property name="redisTemplate" ref="redisTemplate"/>
        <property name="redisSwitch" value="${redis.switch}"/>
        <property name="redisTimeoutDay" value="${redis.timeout.day}"/>
        <property name="redisTimeoutTime" value="${redis.timeout.time}"/>
    </bean>
</beans>

4.RedisCommons.java

package com.common.redis;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.common.pojo.redis.DiscountWrapper;
import com.common.util.DateTimeUtils;
import com.common.util.ObjectUtils;
import com.common.util.Pager;

/**
 * redis公共类.
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class RedisCommons {

	private RedisTemplate redisTemplate;
    /**
     * 缓存是否开启,默认开启,true开启,false不开启
     */
    private volatile boolean redisSwitch = true;
    /**
     * redis默认超时天数,单位天
     */
    private int redisTimeoutDay = 1;
    /**
     * redis默认超时时间,时分秒
     */
    private String redisTimeoutTime = "03:00:00";
    /**
     *  影院信息1小时过期
     */
    public static final int DEFAULT_CINEMA_TIMEOUT = 3600;
    
    static StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    
    /**
	 * 淘票数量缓存过期时间,单位分钟
	 */
	public static final int REDIS_TRANSFER_COUNT_TIME = 10;
	
	/**
	 * 淘票列表缓存过期时间,单位分钟
	 */
	public static final int REDIS_TRANSFER_LIST_TIME = 30;
	
    /**
     * 每天创建订单数缓存过期时间
     */
    private String redisOrderTopCountTimeoutTime = "23:59:59";
    
	private static final Logger logger = LoggerFactory
			.getLogger(RedisCommons.class);
    /**
     * 用于限制每日执行次数的场景。
     * 根据传入的redisKey进行自增,若超过计数上限topCount返回false,否则返回true
     * 建议在key中增加当日日期,以确保每天的count是新的。
     * @param redisKey 场景对应的redisKey
     * @param topCount 计数上限
     * @return 超过计数上限topCount返回false,否则返回true
     */
    public boolean increaseOneCountInDay(String redisKey,String hashKey, int topCount ) {
    	try {
    		BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(redisKey);
            if(boundHashOperations.get(hashKey) == null) {
            	boundHashOperations.put(hashKey,"0");
            	//设置缓存过期时间
            	String date = DateTime.now().toString(DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
            	boundHashOperations.expireAt(DateTimeUtils.createDate(date, redisOrderTopCountTimeoutTime));
            }
            //判断是否超过上限
            return boundHashOperations.increment(hashKey, 1) <= topCount;
		} catch (Exception e) {
			logger.error("increaseOneCountInDay error:",e);
		}
    	//异常情况,保证流程走下去
    	return true;
    }

    /**
     * 将 key 的值设为 value ,当且仅当 key 不存在
     * @param redisKey
     * @param timeout
     * @param unit
     * @return 不存在,set 成功 = true;已经存在=false
     */
    public boolean setIfAbsent(String redisKey,long timeout, TimeUnit unit) {
    	return setIfAbsent(redisKey, "", timeout, unit);

    }
    
    /**
     * 原子check&set操作
     * @param redisKey
     * @param value
     * @param timeout
     * @param unit
     * @return
     */
    public boolean setIfAbsent(String redisKey,String value,long timeout, TimeUnit unit) {
    	boolean result = false;
    	if(redisSwitch){
        	try {
        		BoundValueOperations boundValueOperations = redisTemplate.boundValueOps(redisKey);
        		result = boundValueOperations.setIfAbsent(value);
        		if(result){
        			boundValueOperations.expire(timeout, unit);
        		}
    		} catch (Exception e) {
    			logger.error("setIfAbsent error:",e);
    		}
    	}
        return result;
    }
    
    /**
     * 添加redis缓存
     * 
     * @date 2014年7月10日
     * @param redisKey
     * @param object
     */
    public void set(String redisKey, Object object){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(object)){
    				BoundValueOperations operations = redisTemplate.boundValueOps(redisKey);
    				operations.set(JSON.toJSONString(object));
    				//设置缓存过期时间
    				String date = DateTime.now().plusDays(redisTimeoutDay).toString(DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
    				operations.expireAt(DateTimeUtils.createDate(date, redisTimeoutTime));
    			}
    		} catch (Throwable e) {
    			logger.error("set error:",e);
    		}
    	}
    }
    
    /**
     * 添加redis缓存,设置超时时间
     * 
     * @date 2014年7月15日
     * @param redisKey 缓存key
     * @param object 缓存对象
     * @param date 超时时间点
     */
    public void set(String redisKey, Object object, Date date){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(object)){
    				BoundValueOperations operations = redisTemplate.boundValueOps(redisKey);
    				operations.set(JSON.toJSONString(object));
    				operations.expireAt(date);
    			}
    		} catch (Throwable e) {
    			logger.error("set error:",e);
    		}
    	}
    }
    
    /**
     * 添加redis缓存,设置超时时间
     * 此超时时间会覆盖掉前一个超时时间
     * 
     * @date 2014年7月15日
     * @param redisKey 缓存key
     * @param object 缓存对象
     * @param timeout 超时时间
     * @param unit 超时单位
     */
    public void set(String redisKey, Object object, long timeout, TimeUnit unit){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(object)){
    				redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(object), timeout, unit);
    			}
    		} catch (Throwable e) {
    			logger.error("set error:",e);
    		}
    	}
    }
    
    /**
     * 不设置超时时间的set方法
     * @param redisKey
     * @param object
     */
    public void setNoExpire(String redisKey, Object object){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(object)){
    				BoundValueOperations operations = redisTemplate.boundValueOps(redisKey);
    				operations.set(JSON.toJSONString(object));
    			}
    		} catch (Throwable e) {
    			logger.error("set error:",e);
    		}
    	}
    }
    
    /**
     * 添加redis的map缓存
     * 
     * @date 2014年7月10日
     * @param redisKey
     * @param hashKey
     * @param object
     */
    public void hset(String redisKey, String hashKey, Object object){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(object)){
    				BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(redisKey);
    				boundHashOperations.put(hashKey, JSON.toJSONString(object));
    				//设置缓存过期时间
    				String date = DateTime.now().plusDays(redisTimeoutDay).toString(DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
    				boundHashOperations.expireAt(DateTimeUtils.createDate(date, redisTimeoutTime));
    			}
    		} catch (Throwable e) {
    			logger.error("hset error:",e);
    		}
    	}
    }
    
    /**
     * 添加redis的map缓存,当天过期
     * 
     * @date 2014年7月10日
     * @param redisKey
     * @param hashKey
     * @param object
     */
    public void hsetExpireAtToday(String redisKey, String hashKey, Object object){
    	if(redisSwitch){
    		try {
    			if(object != null){
    				BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(redisKey);
    				boundHashOperations.put(hashKey, JSON.toJSONString(object, SerializerFeature.WriteNullListAsEmpty));
    				//设置缓存过期时间
    				String date = DateTime.now().toString(DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
    				boundHashOperations.expireAt(DateTimeUtils.createDate(date, redisOrderTopCountTimeoutTime));
    			}
    		} catch (Throwable e) {
    			logger.error("hset error:",e);
    		}
    	}
    }
    
    public void hsetJudgeExpire(String redisKey, String hashKey, Object object){
    	if(redisSwitch){
    		try {
    			BoundHashOperations<String,String,String> boundHashOperations = redisTemplate.boundHashOps(redisKey);
				boundHashOperations.put(hashKey, JSON.toJSONString(object));
				if(boundHashOperations.getExpire() < 0){
					boundHashOperations.expire(DEFAULT_CINEMA_TIMEOUT, TimeUnit.SECONDS);
				}
    		} catch (Throwable e) {
    			logger.error("hset error:",e);
    		}
    	}
    }
    
    public void hsetNoExpire(String redisKey, String hashKey, Object object){
       	if(redisSwitch){
    		try {
    			BoundHashOperations<String,String,String> boundHashOperations = redisTemplate.boundHashOps(redisKey);
				boundHashOperations.put(hashKey, JSON.toJSONString(object));
    		} catch (Throwable e) {
    			logger.error("hset error:",e);
    		}
    	}
    }

    public void expire(String redisKey,int seconds){
    	if(redisSwitch){
    		try{
    			BoundValueOperations opt = redisTemplate.boundValueOps(redisKey);
    			opt.expire(seconds, TimeUnit.SECONDS);
    		}catch (Throwable e) {
    			logger.error("expire error:",e);
    		}
    	}
    }
    
    /**
     * 添加redis的map缓存,设置超时时间
     * 
     * @date 2014年7月18日
     * @param redisKey 缓存key
     * @param hashKey 
     * @param object 缓存对象
     * @param date 超时时间点
     */
    public void hset(String redisKey, String hashKey, Object object, Date date){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(object)){
    				BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(redisKey);
    				boundHashOperations.put(hashKey, JSON.toJSONString(object));
    				boundHashOperations.expireAt(date);
    			}
    		} catch (Throwable e) {
    			logger.error("hset error:",e);
    		}
    	}
    }
    
    /**
     * 添加redis的map缓存,设置超时时间
     * 此超时时间会覆盖掉前一个超时时间
     * 
     * @date 2014年7月15日
     * @param redisKey 缓存key
     * @param hashKey 
     * @param object 缓存对象
     * @param timeout 超时时间
     * @param unit 超时单位
     */
    public void hset(String redisKey, String hashKey, Object object, long timeout, TimeUnit unit){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(object)){
    				BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(redisKey);
    				boundHashOperations.put(hashKey, JSON.toJSONString(object));
    				boundHashOperations.expire(timeout, unit);
    			}
    		} catch (Throwable e) {
    			logger.error("hset error:",e);
    		}
    	}
    }
    
    public void hsetAll(String redisKey,Map<String,String> map, long timeout, TimeUnit unit){
    	if(redisSwitch){
    		try {
    				BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(redisKey);
    				boundHashOperations.putAll(map);
    				boundHashOperations.expire(timeout, unit);
    		} catch (Throwable e) {
    			logger.error("hsetAll error:",e);
    		}
    	}
    }
    
    /**
     * 获取redis非list缓存
     * 
     * @date 2014年7月10日
     * @param redisKey
     * @param clazz
     * @return
     */
    public <T> T get(String redisKey, Class<T> clazz){
    	if(redisSwitch){
    		try {
    			String objectJson = (String) redisTemplate.opsForValue().get(redisKey);
    			if(StringUtils.isBlank(objectJson)){
    				return null;
    			}
    			return JSON.parseObject(objectJson, clazz);
    		} catch (Throwable e) {
    			logger.error("get error:",e);
    		}
    	}
    	return null;
    }


	public Long increment(String redisKey,String hashKey, long delta ){
		if(redisSwitch){
			return redisTemplate.opsForHash().increment(redisKey,hashKey,delta);
		}
		return null;
	}
    
    public LinkedHashMap<Long, DiscountWrapper> getLinkedHashMap(String redisKey){
    	if(redisSwitch){
    		String s = (String) redisTemplate.opsForValue().get(redisKey);
    		if(StringUtils.isBlank(s)){
    			return null;
    		}
    		return JSON.parseObject(s,new TypeReference<LinkedHashMap<Long, DiscountWrapper>>(){});
    	}
    	return null;
    }
    
    /**
     * 获取redis的list缓存
     * 
     * @date 2014年7月10日
     * @param redisKey
     * @param clazz
     * @return
     */
    public <T> List<T> getList(String redisKey, Class<T> clazz){
    	if(redisSwitch){
    		try {
    			String objectJson = (String) redisTemplate.opsForValue().get(redisKey);
    			if(StringUtils.isBlank(objectJson)){
    				return new ArrayList<T>();
    			}
    			return JSON.parseArray(objectJson, clazz);
    		} catch (Throwable e) {
    			logger.error("getList error:",e);
    		}
    	}
    	
    	return new ArrayList<T>();
    }
    
    /**
     * 获取redis的map缓存
     * 
     * @date 2014年7月10日
     * @param redisKey
     * @param hashKey
     * @param clazz
     * @return
     */
    public <T> T hget(String redisKey, String hashKey, Class<T> clazz){
    	if(redisSwitch){
    		try {
    			String objectJson = (String) redisTemplate.opsForHash().get(redisKey, hashKey);
    			if(StringUtils.isBlank(objectJson)){
    				return null;
    			}
    			return JSON.parseObject(objectJson, clazz);
    		} catch (Throwable e) {
    			logger.error("hget error:",e);
    		}
    	}
    	return null;
    }
    
    /**
     * 获取redis中map的list缓存
     * 
     * @date 2014年7月10日
     * @param redisKey
     * @param hashKey
     * @param clazz
     * @return
     */
	public <T> List<T> hgetList(String redisKey, String hashKey, Class<T> clazz){
    	if(redisSwitch){
    		try {
    			String objectJson = (String) redisTemplate.opsForHash().get(redisKey, hashKey);
    			if(StringUtils.isBlank(objectJson)){
    				return null;
    			}
    			return JSON.parseArray(objectJson, clazz);
    		} catch (Throwable e) {
    			logger.error("hgetList error:",e);
    		}
    	}
    	return new ArrayList<T>();
    }
    
    /**
     * 删除redis某个key的缓存
     * 
     * @date 2014年7月10日
     * @param redisKey
     */
    public void delete(String redisKey){
    	if(redisSwitch){
    		try {
				redisTemplate.delete(redisKey);
			} catch (Throwable e) {
				logger.error("delete error:",e);
			}
    	}
    }
    
    /**
     * 模糊匹配删除redis某些key的缓存
     * 
     * @date 2014年7月10日
     * @param redisKey
     */
    public void deleteFuzzy(String fuzzyRedisKey){
    	if(redisSwitch){
    		try {
    			redisTemplate.delete(redisTemplate.keys(fuzzyRedisKey));
			} catch (Throwable e) {
				logger.error("delete error:",e);
			}
    	}
    }
    
    /**
     * 删除redis中map的key
     * 
     * @date 2014年7月10日
     * @param redisKey
     * @param hashKey
     */
    public void hdelete(String redisKey, String... hashKeys){
    	if(redisSwitch){
    		try {
				redisTemplate.opsForHash().delete(redisKey, hashKeys);
			} catch (Throwable e) {
				logger.error("hdelete error:",e);
			}
    	}
    }
    
	public Long zadd(String key, Set<TypedTuple<String>> tuples,long second){
    	if(redisSwitch){
    		try{
    			BoundZSetOperations<String,String> opt = redisTemplate.boundZSetOps(key);
    			Long result = opt.add(tuples);
    			opt.expire(second, TimeUnit.SECONDS);
    			return result;
    		}catch(Throwable e){
    			logger.error("zdd error:",e);
    		}
    	}
    	return null;
    }

	public  Set<TypedTuple<String>> zrange(String redisKey,Pager pager){
    	if(redisSwitch){
    		try{
    			long start = 0;
    			long end = -1;
    			if(pager != null && !pager.isAll()){
    				start = (pager.getPageIndex()-1)*pager.getPageNum();
            		end = start + pager.getPageNum() - 1;
    			}
        		ZSetOperations<String, String> opt = redisTemplate.opsForZSet();
        		return opt.rangeWithScores(redisKey, start, end);
    		}catch(Throwable e){
    			logger.error("zrange error:",e);
    		}
    	}
    	return null;
    }
    
    public long zcard (String redisKey){
    	if(redisSwitch){
    		try{
    			ZSetOperations<String, String> opt = redisTemplate.opsForZSet();
    			return opt.zCard(redisKey);
    		}catch(Throwable e){
    			logger.error("zcard error:",e);
    		}
    	}
    	return 0;
    }
    
    public boolean zadd(String redisKey,Object value,double score){
    	if(redisSwitch){
    		BoundZSetOperations<String,String> opt = redisTemplate.boundZSetOps(redisKey);
    		return opt.add(JSON.toJSONString(value), score);
    	}
    	return false;
    }
    
    public boolean zdelete(String redisKey, Object value){
    	if(redisSwitch){
    		BoundZSetOperations<String,String> opt = redisTemplate.boundZSetOps(redisKey);
    		Long result = opt.remove(JSON.toJSONString(value));
    		if(result != null && result == 1){
    			return true;
    		}
    	}
    	return false;
    }
    
    public <T> Set<T> zrange(String redisKey,double min,double max, Class<T> clazz){
    	if(redisSwitch){
    		BoundZSetOperations<String,String> opt = redisTemplate.boundZSetOps(redisKey);
    		Set<String> set = opt.rangeByScore(min, max);
    		Set<T> result = new LinkedHashSet<T>(set.size());
    		for(String s : set){
    			T t = JSON.parseObject(s, clazz);
    			result.add(t);
    		}
    		return result;
    	}
    	
    	return null;
    }
    
    public void zremRangeByScore(String redisKey,double min,double max){
    	if(redisSwitch){
    		BoundZSetOperations<String,String> opt = redisTemplate.boundZSetOps(redisKey);
    		opt.removeRangeByScore(min, max);
    	}
    }
    
    public Map<String,String> hgetall(String key){
    	if(redisSwitch){
    		try{
    			HashOperations<String, String, String> opt = redisTemplate.opsForHash();
    			return opt.entries(key);
    		}catch(Throwable e){
    			logger.error("hgetall error:",e);
    		}
    	}
    	return null;
    }
    
    public List<Map<String,String>> hgetallBatch(final List<String> redisKeys){
    	if(redisSwitch){
    		try{
    			RedisCallback callback = new RedisCallback() {
					@Override
					public Object doInRedis(
							RedisConnection connection)
							throws DataAccessException {
						for(String redisKey: redisKeys){
							connection.hGetAll(redisKey.getBytes());
						}
						return null;
					}
				};
				return (List<Map<String,String>>)redisTemplate.executePipelined(callback, stringRedisSerializer);
    		}catch(Throwable e){
    			logger.error("hgetall error:",e);
    		}
    	}
    	return null;
    }

    /**
     * 根据hashkeys列表获取缓存列表
     * 
     * @date 2014年7月26日
     * @param key
     * @param hashKeys
     * @return
     */
    public List<String> hgetall(String key, Collection<String> hashKeys){
    	if(redisSwitch){
    		try{
    			HashOperations<String, String, String> opt = redisTemplate.opsForHash();
    			return opt.multiGet(key, hashKeys);
    		}catch(Throwable e){
    			logger.error("hgetall error:",e);
    		}
    	}
    	return null;
    }
    
    public <T> List<T> hgetall(String key, Collection<String> hashKeys, Class<T> targetClass){
    	if(redisSwitch){
    		try{
    			HashOperations<String, String, String> opt = redisTemplate.opsForHash();
    			List<String> jsonList = opt.multiGet(key, hashKeys);
    			if(jsonList != null && !jsonList.isEmpty()){
    				return JSON.parseArray(jsonList.toString(), targetClass);
    			}
    		}catch(Throwable e){
    			logger.error("hgetall error:",e);
    		}
    	}
    	return null;
    }
    
    public List<String> hgetBatch(final String redisKey, final List<String> hashKeys){
    	if(redisSwitch){
    		try{
    			RedisCallback callback = new RedisCallback() {
					@Override
					public Object doInRedis(
							RedisConnection connection)
							throws DataAccessException {
						for(String hashKey: hashKeys){
							connection.hGet(redisKey.getBytes(), hashKey.getBytes());
						}
						return null;
					}
				};
				return (List<String>)redisTemplate.executePipelined(callback, stringRedisSerializer);
    		}catch(Throwable e){
    			logger.error("hgetBatch error:",e);
    		}		
    	}
    	return null;
    }    
    
    public List<Map<String,String>> hgetBatch(final List<String> redisKeys, final String hkey){
    	if(redisSwitch){
    		try{
    			RedisCallback callback = new RedisCallback() {
					@Override
					public Object doInRedis(
							RedisConnection connection)
							throws DataAccessException {
						for(String redisKey: redisKeys){
							//key is English.All charset ok.
							connection.hGet(redisKey.getBytes(),hkey.getBytes());
						}
						return null;
					}
				};
				return (List<Map<String,String>>)redisTemplate.executePipelined(callback, stringRedisSerializer);
    		}catch(Throwable e){
    			logger.error("hgetall error:",e);
    		}
    	}
    	return null;
    }

    //start list api
    /**
     * 添加redis的List缓存, 默认当前23:59:59失效
     * 
     * @date 2014年12月29日
     * @param redisKey
     * @param object
     */
    public void rpush(String redisKey, Object... objects){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(objects)){
    				BoundListOperations operations = redisTemplate.boundListOps(redisKey);
    				operations.rightPushAll(objects);
    				//设置缓存过期时间
                	String date = DateTime.now().toString(DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
                	operations.expireAt(DateTimeUtils.createDate(date, redisOrderTopCountTimeoutTime));
    			}
    		} catch (Throwable e) {
    			logger.error("set error:",e);
    		}
    	}
    }
    
    /**
     * 添加redis的List缓存
     * 
     * @date 2014年12月29日
     * @param redisKey
     * @param timeout 失效时间
     * @param unit 时间单位
     * @param objects
     */
    public void rpush(String redisKey, long timeout, TimeUnit unit, Object... objects){
    	if(redisSwitch){
    		try {
    			if(ObjectUtils.isNotEmpty(objects)){
    				BoundListOperations operations = redisTemplate.boundListOps(redisKey);
    				operations.rightPushAll(objects);
    				//设置缓存过期时间
                	String date = DateTime.now().toString(DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
                	operations.expireAt(DateTimeUtils.createDate(date, redisOrderTopCountTimeoutTime));
    			}
    		} catch (Throwable e) {
    			logger.error("set error:",e);
    		}
    	}
    }
    
    /**
     * 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定:[0, 10]
     * 
     * @param <T>
     * @date 2014年12月29日
     * @param redisKey
     * @param object
     */
    public <T> List<T> lrange(String redisKey, Pager pager){
    	if(redisSwitch){
    		try {
    			long start = 0;
    			long end = -1;
    			if(pager != null && !pager.isAll()){
    				start = (pager.getPageIndex()-1)*pager.getPageNum();
            		end = start + pager.getPageNum() - 1;
    			}
    			BoundListOperations operations = redisTemplate.boundListOps(redisKey);
				return operations.range(start, end);
    		} catch (Throwable e) {
    			logger.error("set error:",e);
    		}
    	}
    	return null;
    }
    	
    //end list api
    
    
    
    /**
     * redis的set数据结构的数据增加。
     * @param key redis key
     * @param values values
     * @param second 过期时间
     * @return 增加的记录数
     */
    public Long sAdd(String key, List<String> values, long second){
        if(redisSwitch){
            try{
                BoundSetOperations boundSetOperations = redisTemplate.boundSetOps(key);
                Long result = boundSetOperations.add(values.toArray());
                if(second > 0) {
                    boundSetOperations.expire(second, TimeUnit.SECONDS);
                }
                return result;
            }catch(Throwable e){
                logger.error("sAdd error:",e);
            }
        }
        return 0L;
    }

    /**
     * redis set的记录数。
     * @param key  redis key
     * @return set的记录数
     */
    public Long sCard(String key){
        if(redisSwitch){
            try{
                return redisTemplate.boundSetOps(key).size();
            }catch(Throwable e){
                logger.error("sAdd error:",e);
            }
        }
        return 0L;
    }

    /**
     * 弹出redis set的一条记录。
     * @param key redis key
     * @return set value
     */
    public String sPop(String key){
        if(redisSwitch){
            try{
                return (String) redisTemplate.boundSetOps(key).pop();
            }catch(Throwable e){
                logger.error("sPop error:",e);
            }
        }
        return null;
    }

    public boolean sIsMember(String key, String value){
        if(redisSwitch){
            try{
                return redisTemplate.boundSetOps(key).isMember(value);
            }catch(Throwable e){
                logger.error("sIsMember error:",e);
            }
        }
        return true;
    }

    /**
     * 求差集
     * @param key 源key
     * @param otherKey 其他key
     * @param destKey 目标key
     */
    public void sdiffAndStore(String key, String otherKey, String destKey){
    	if(redisSwitch){
            try{
            	redisTemplate.boundSetOps(key).diffAndStore(otherKey, destKey);
            }catch(Throwable e){
                logger.error("sdiffAndStore error:",e);
            }
        }
    }
    
    /**
     * 是否存在key
     * @param key
     * @return
     */
    public boolean exist(String key){
    	boolean result = false;
    	if(redisSwitch){
    		result = redisTemplate.hasKey(key);
    	}
    	return result;
    }

    /**
     * 重置redis的过期时间
     * @param redisKey
     * @return
     */
    public boolean resetExpireTime(String redisKey, long timeout, TimeUnit unit) {
        if(redisSwitch){
            try {
                return redisTemplate.boundValueOps(redisKey).expire(timeout, unit);
            } catch (Exception e) {
                logger.error("resetExpireTime error:",e);
                return false;
            }
        }
        return true;
    }

    public int incr(String key, int i){
    	if(redisSwitch){
    		Long l = redisTemplate.boundValueOps(key).increment(i);
    		if(l != null){
    			return l.intValue();
    		}
    	}
    	return -1;
    }
    
    public int decr(String key, int i){
    	if(redisSwitch){
    		Long l = redisTemplate.boundValueOps(key).increment(-i);
    		if(l != null){
    			return l.intValue();
    		}
    	}
    	return -1;
    }
    
    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

	public boolean isRedisSwitch() {
		return redisSwitch;
	}

	public void setRedisSwitch(boolean redisSwitch) {
		this.redisSwitch = redisSwitch;
	}

	public int getRedisTimeoutDay() {
		return redisTimeoutDay;
	}

	public void setRedisTimeoutDay(int redisTimeoutDay) {
		this.redisTimeoutDay = redisTimeoutDay;
	}

	public String getRedisTimeoutTime() {
		return redisTimeoutTime;
	}

	public void setRedisTimeoutTime(String redisTimeoutTime) {
		this.redisTimeoutTime = redisTimeoutTime;
	}
	
}

5.RedisTest

package com.api.util;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;
import com.api.dao.CinemaDAO;
import com.common.consts.RedisKeyConstants;
import com.common.pojo.redis.FilmRedis;
import com.common.redis.RedisCommons;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/spring/applicationContext-base.xml","classpath:/spring/applicationContext-dao.xml","classpath:/spring/applicationContext-cache.xml"})
public class RedisTest {

	@Resource
	private RedisTemplate<String, String> redisTemplate;
	
	@Resource
	private CinemaDAO cinemaDAO;
	
	@Test
	public void deleteKey(){
		//redisTemplate.delete(RedisKeyConstants.FILM);
		//redisTemplate.delete(RedisKeyConstants.CINEMA_FILMS);
		redisTemplate.delete(RedisKeyConstants.TRANSFERRED_LIST + 1);
	}
	
	@Test
	public void getKey(){
		RedisCommons redisCommons = new RedisCommons();
		redisCommons.setRedisTemplate(redisTemplate);
		System.err.println(redisTemplate.opsForHash().get(RedisKeyConstants.FILM, "2050"));
		System.err.println(redisTemplate.opsForHash().get(RedisKeyConstants.FILM_HOTS, "315"));
		
		//System.err.println(redisTemplate.opsForHash().get(RedisKeyConstants.CINEMA_FILMS, "25018"));
		//List<FilmRedis> filmRedisList = redisCommons.hgetall(RedisKeyConstants.FILM, Arrays.asList("1", "2", "3"), FilmRedis.class);
		//System.err.println(JSON.toJSONString(filmRedisList));
	}
	
//	@Test
//	public void SetKey(){
//		redisTemplate.opsForHash().put(RedisKeyConstants.CINEMA, "cinema_jijun", "jijun");
//	}
	
	@Test
	public void testHasKey(){
		System.out.println(redisTemplate.keys(RedisKeyConstants.FILM_HOTS + "*"));
	}
	
	@Test
	public void clearRedis(){
		//命令删除:/usr/bin/redis-cli keys "tickets.*" | xargs /usr/bin/redis-cli del
		redisTemplate.delete(redisTemplate.keys("tickets.*"));
	}
}

猜你喜欢

转载自dk05408.iteye.com/blog/2219452
今日推荐