Spring data redis工具类

647 阅读1分钟
package com.hxkj.fsslr.core.utils;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * ClassName:RedisUtils 
 * Function: redis操作工具类
 * @author huzhihui_c@qq.com Date: 2016年7月17日 下午2:49:45
 * @version 1.0
 * @since JDK 1.8
 */
public class RedisUtils {

	@SuppressWarnings("rawtypes")
	private static RedisTemplate redisTemplate = (RedisTemplate) SpringContextUtils
			.getBean("redisTemplate");
	
	/**
	 * @Function: 
	 * @Title: save  
	 * @param key
	 * @param value
	 * @return   
	 * boolean    
	 * @author huzhihui_c@qq.com   
	 * @date 2016年7月17日 下午3:36:36
	 * @Since JDK 1.8
	 */
	@SuppressWarnings("unchecked")
	public static boolean save(final String key,Object value){
		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(key,value);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			return result;
		}
		return result;
	}
	
	/**
	 * @Function: 保存redis,需要传入保存时间
	 * @Title: save  
	 * @param key
	 * @param value
	 * @param saveTime
	 * boolean    
	 * @author huzhihui_c@qq.com   
	 * @date 2016年7月17日 下午3:40:21
	 * @Since JDK 1.8
	 */
	@SuppressWarnings("unchecked")
	public static boolean save(final String key,Object value,Long saveTime){
		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(key,value);
			redisTemplate.expire(key, saveTime, TimeUnit.SECONDS);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			return result;
		}
		return result;
	}
	
	/**
	 * @Function: 通过key值得到value
	 * @Title: get  
	 * @param key
	 * @return   
	 * Object    
	 * @author huzhihui_c@qq.com   
	 * @date 2016年7月17日 下午3:49:21
	 * @Since JDK 1.8
	 */
	@SuppressWarnings("unchecked")
	public static Object get(final String key){
		Object result = null;
		ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
		result = operations.get(key);
		return result;
	}
	
	/**
	 * @Function: 检查是否存在该key-value键值对
	 * @Title: exists  
	 * @param key
	 * @return   
	 * boolean    
	 * @author huzhihui_c@qq.com   
	 * @date 2016年7月17日 下午3:52:08
	 * @Since JDK 1.8
	 */
	@SuppressWarnings("unchecked")
	public static boolean exists(final String key){
		return redisTemplate.hasKey(key);
	}
	
	/**
	 * @Function: 删除一个key-value键值对
	 * @Title: remove  
	 * @param key   
	 * void    
	 * @author huzhihui_c@qq.com   
	 * @date 2016年7月17日 下午3:53:41
	 * @Since JDK 1.8
	 */
	@SuppressWarnings("unchecked")
	public static void remove(final String key){
		if(exists(key)){
			redisTemplate.delete(key);
		}
	}
	
}