redis工具类

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.sf.json.JSONSerializer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.exceptions.JedisException;

/**
 * Redis工具类
 * 以ShardedJedisPool的方式操作redis
 * 极大提高操作效率
 */
public class RedisUtil { 
	private static Log log = LogFactory.getLog(RedisUtil.class);

	private Integer maxActive = 500;
	private Integer maxIdle = 1000;
	private Integer maxWait = 60;
	private String address = "127.0.0.1:6379";
	private ShardedJedisPool pool;

	/**
	 * 初始化 Redis
	 */
	public void init() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxActive(maxActive);
		config.setMaxIdle(maxIdle);
		config.setMaxWait(maxWait);
		config.setTestOnBorrow(false); 
		
		List<JedisShardInfo> list = new ArrayList<JedisShardInfo>();
		String[] addressArr = address.split(",");
		for (String str : addressArr) {
			list.add(new JedisShardInfo(str.split(":")[0], Integer.parseInt(str
					.split(":")[1])));
		}
		pool = new ShardedJedisPool(config, list);
	}

	/**
	 * 关闭 Redis
	 */
	public void destory() {
		pool.destroy();
	}
	
	/**
	 * 
	 * @param key
	 * @return
	 */
	public long del(String key) {
		ShardedJedis shardedJedis = null;
		long ret = 0l;
		try {
			shardedJedis = pool.getResource(); 
			ret = shardedJedis.del(key);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return ret;
	}

	/**
	 * 
	 * @param key
	 * @param fields
	 * @return
	 */
	public long hdel(String key,String... fields) {
		
		ShardedJedis shardedJedis = null;
		long ret = 0l;
		try {
			shardedJedis = pool.getResource();
			ret = shardedJedis.hdel(key, fields);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return ret;
	}
	
	/**
	 * 给key赋值,并生命周期设置为seconds  
	 * 
	 * @param key
	 * @param seconds
	 *            生命周期 秒为单位
	 * @param tsUser
	 */
	public void setTSUser(String key, int seconds, TSUser tsUser) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			String userString = "";
			if(tsUser!=null){
			   //以下代码防止懒加载或无限循环问题
		       if(tsUser.getDefaultOrg()!=null){
		    	   tsUser.getDefaultOrg().setParentOrg(null);
		    	   tsUser.getDefaultOrg().setSubOrgs(null);
		       }
		       if(tsUser.getTmEmployee()!=null&&tsUser.getTmEmployee().getTmOrg()!=null){
		    	   tsUser.getTmEmployee().getTmOrg().setParentOrg(null);
		    	   tsUser.getTmEmployee().getTmOrg().setSubOrgs(null);
		    	   tsUser.getTmEmployee().setTmPosition(null);
		       }
		        tsUser.setOplistSet(null);
		        tsUser.setTSDepart(null);
		     
				String json = "";//JSONSerializer.toJSON(tsUser).toString();
				json= JSONObject.toJSONString(tsUser);
				userString =  json.toString();
			} 
			shardedJedis.setex(key, seconds, userString);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}
	
	/**
	 * 通过Key 获取用户
	 * 
	 * @param key
	 * @return
	 */
	public TSUser getTSUser(String key) {
		ShardedJedis shardedJedis = null;
		String value = null;
		TSUser tsUser =  null;
		try {
			shardedJedis = pool.getResource();
			value = shardedJedis.get(key); 
//		    JSONObject userJson = JSONObject.parseObject(value);
//			tsUser = JSON.toJavaObject(userJson,TSUser.class);
			tsUser = JSONObject.parseObject(value,TSUser.class);

			//刷新token过期时间
			expire(key,30*60);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return tsUser;
	}
	
	
	
	/**
	 * redis的List集合 ,向key这个list添加元素
	 * 
	 * @param key
	 *            List别名
	 * @param string
	 *            元素
	 * @return
	 */
	public long rpush(String key, String string) {
		ShardedJedis shardedJedis = null;
		long ret = 0l;
		try {
			shardedJedis = pool.getResource();
			ret = shardedJedis.rpush(key, string); 
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return ret;
	}

	/**
	 * 获取key这个List,从第几个元素到第几个元素 LRANGE key start
	 * stop返回列表key中指定区间内的元素,区间以偏移量start和stop指定。
	 * 下标(index)参数start和stop都以0为底,也就是说,以0表示列表的第一个元素,以1表示列表的第二个元素,以此类推。
	 * 也可以使用负数下标,以-1表示列表的最后一个元素,-2表示列表的倒数第二个元素,以此类推。
	 * 
	 * @param key
	 *            List别名
	 * @param start
	 *            开始下标
	 * @param end
	 *            结束下标
	 * @return
	 */
	public List<String> lrange(String key, long start, long end) {
		ShardedJedis shardedJedis = null;
		List<String> ret  = null;
		try {
			shardedJedis = pool.getResource();
			ret = shardedJedis.lrange(key, start, end);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return ret;
	}

	/**
	 * 将哈希表key中的域field的值设为value。
	 * 
	 * @param key
	 *            哈希表别名
	 * @param field键
	 * @param value
	 *            值
	 */
	public void hset(String key, String field, String value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.hset(key, field, value);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}

	/**
	 * 向key赋值
	 * 
	 * @param key
	 * @param value
	 */
	public void set(String key, String value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.set(key, value);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}
	
	/**
	 * 向key赋值
	 * @param key
	 * @param value
	 */
	public void set(byte [] key, byte [] value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.set(key, value);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}
	
	/**
	 * 获取key的值
	 * 
	 * @param key
	 * @return
	 */
	public byte[] get(byte[] key) {
		ShardedJedis shardedJedis = null;
		byte[] value = null;
		try {
			shardedJedis = pool.getResource();
			value = shardedJedis.get(key);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return value;
	}

	/**
	 * 获取key的值
	 * 
	 * @param key
	 * @return
	 */
	public String get(String key) {
		ShardedJedis shardedJedis = null;
		String value = null;
		try {
			shardedJedis = pool.getResource();
			value = shardedJedis.get(key);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return value;
	}

	/**
	 * 将多个field - value(域-值)对设置到哈希表key中。
	 * 
	 * @param key
	 * @param map
	 */
	public void hmset(String key, Map<String, String> map) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.hmset(key, map);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}

	/**
	 * 给key赋值,并生命周期设置为seconds
	 * 
	 * @param key
	 * @param seconds
	 *            生命周期 秒为单位
	 * @param value
	 */
	public void setex(String key, int seconds, String value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.setex(key, seconds, value);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}
	
	/**
	 * 为给定key设置生命周期
	 * 
	 * @param key
	 * @param seconds
	 *            生命周期 秒为单位
	 */
	public void expire(byte[] key, int seconds) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.expire(key, seconds);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}

	/**
	 * 为给定key设置生命周期
	 * 
	 * @param key
	 * @param seconds
	 *            生命周期 秒为单位
	 */
	public void expire(String key, int seconds) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.expire(key, seconds);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}

	/**
	 * 检查key是否存在
	 * 
	 * @param key
	 * @return
	 */
	public boolean exists(String key) {
		ShardedJedis shardedJedis = null;
		boolean bool = false;
		try {
			shardedJedis = pool.getResource();
			bool = shardedJedis.exists(key);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return bool;
	}

	/**
	 * 返回key值的类型 none(key不存在),string(字符串),list(列表),set(集合),zset(有序集),hash(哈希表)
	 * 
	 * @param key
	 * @return
	 */
	public String type(String key) {
		ShardedJedis shardedJedis = null;
		String type =null;
		try {
			shardedJedis = pool.getResource();
			type = shardedJedis.type(key);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return type;
	}

	/**
	 * 从哈希表key中获取field的value
	 * 
	 * @param key
	 * @param field
	 */
	public String hget(String key, String field) {
		ShardedJedis shardedJedis = null;
		String value =null;
		try {
			shardedJedis = pool.getResource();
			value = shardedJedis.hget(key, field);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return value;
	}

	/**
	 * 返回哈希表key中,所有的域和值
	 * 
	 * @param key
	 * @return
	 */
	public Map<String, String> hgetAll(String key) {
		ShardedJedis shardedJedis = null;
		Map<String, String> map =null;
		try {
			shardedJedis = pool.getResource();
			map = shardedJedis.hgetAll(key);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return map;
	}

	/**
	 * 返回哈希表key中,所有的域和值
	 * 
	 * @param key
	 * @return
	 */
	public Set<?> smembers(String key) {
		ShardedJedis shardedJedis = null;
		Set<?> set =null;
		try {
			shardedJedis = pool.getResource();
			set = shardedJedis.smembers(key);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return set;
	}

	/**
	 * 移除集合中的member元素
	 * 
	 * @param key
	 *            List别名
	 * @param field
	 *            键
	 */
	public void delSetObj(String key, String field) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.srem(key, field);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}

	/**
	 * 判断member元素是否是集合key的成员。是(true),否则(false)
	 * 
	 * @param key
	 * @param field
	 * @return
	 */
	public boolean isNotField(String key, String field) {
		ShardedJedis shardedJedis = null;
		boolean bool = false;
		try {
			shardedJedis = pool.getResource();
			bool = shardedJedis.sismember(key, field);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
		return bool;
	}

	/**
	 * 如果key已经存在并且是一个字符串,将value追加到key原来的值之后
	 * 
	 * @param key
	 * @param value
	 */
	public void append(String key, String value) {
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			shardedJedis.append(key, value);
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}
	
	public Set<String> getAllKeys(){
		ShardedJedis shardedJedis = null;
		Set<String> keys = new HashSet<String>();
		try {
			shardedJedis = pool.getResource();
			Collection<Jedis> shards = shardedJedis.getAllShards();
			if(shards != null && !shards.isEmpty()) {
				for (Jedis shard : shards) {
					keys.addAll(shard.keys("*"));
				}
			}
			return keys;
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}
	
	public void flushAll(){
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = pool.getResource();
			Collection<Jedis> shards = shardedJedis.getAllShards();
			if(shards != null && !shards.isEmpty()) {
				for (Jedis shard : shards) {
					shard.flushAll();
				}
			}
		} catch (Exception e) {
			pool.returnBrokenResource(shardedJedis);
			shardedJedis = null;
			log.error(e);
			throw new JedisException(e);
		}finally{
			if (shardedJedis != null) { 
				pool.returnResource(shardedJedis);
			}
		}
	}

	public int getMaxActive() {
		return maxActive;
	}

	public void setMaxActive(int maxActive) {
		this.maxActive = maxActive;
	}
	public Integer getMaxIdle() {
		return maxIdle;
	}
	public void setMaxIdle(Integer maxIdle) {
		this.maxIdle = maxIdle;
	}
	public Integer getMaxWait() {
		return maxWait;
	}
	public void setMaxWait(Integer maxWait) {
		this.maxWait = maxWait;
	}
	public void setMaxActive(Integer maxActive) {
		this.maxActive = maxActive;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	public static void main(String[] args){
		RedisUtil r = new RedisUtil();
		r.init();
		Set<String> keys = r.getAllKeys();
		System.out.println(keys); 
//		r.flushAll();
//		System.out.println(keys);
		TSUser t =  r.getTSUser("eyJhbGciOiJIUzI1NiIsImVuY3J5cHRpb24iOiJIUzI1NiIsInR5cCI6IkpXVCIsInR5cGUiOiJKV1QifQ.eyJleHAiOjE2MzUzMjIxMjIsIlRpbWUiOjE2MzUyMzU3MjIyNTAsInVzZXJDb2RlIjoiYWRtaW4ifQ.ra9t1TyuiHjsuV58MGkX6SKY8hIxy-xS5QGYUfO--iA");
//		r.get("eyJhbGciOiJIUzI1NiIsImVuY3J5cHRpb24iOiJIUzI1NiIsInR5cCI6IkpXVCIsInR5cGUiOiJKV1QifQ.eyJleHAiOjE2MzUzMTY5NzcsIlRpbWUiOjE2MzUyMzA1Nzc2NTksInVzZXJDb2RlIjoiYWRtaW4ifQ.wOQ1eC6q2djSMG4CuNoywoua6FLM--ZOvE_ATr5lix0");
//		System.out.println(r.get("eyJhbGciOiJIUzI1NiIsImVuY3J5cHRpb24iOiJIUzI1NiIsInR5cCI6IkpXVCIsInR5cGUiOiJKV1QifQ.eyJleHAiOjE2MzUzMTk0MDMsIlRpbWUiOjE2MzUyMzMwMDMyMDIsInVzZXJDb2RlIjoiYWRtaW4ifQ.edOlNofAKIJM5osUQS0_B8fe1DD9K_mXMHy-J6WS6xA"));
//		r.set("aaaa", "aaaaa");
//		System.out.println(r.hgetAll("com.ewin.erp.basebus.entity.BillInfo"));
	}
}

里面的TsUser需要删除,没有意义的对象

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值