`

Jedis封装工具类

 
阅读更多
package com.feng;

import com.common.utils.SerializeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class JedisUtil {

	@Autowired
	protected static JedisPool jedisPool;
	private JedisUtil() {}
	
	/**
	 * 简单的Get
	 * @param <T>
	 * @param key
	 * @param requiredType
	 * @return
	 */
	public static <T> T get(String key , Class<T>...requiredType){
		Jedis jds = null;
        boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] skey = SerializeUtil.serialize(key);
			return SerializeUtil.deserialize(jds.get(skey),requiredType);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
		return null;
	}
	/**
	 * 简单的set
	 * @param key
	 * @param value
	 */
	public static void set(Object key ,Object value){
		Jedis jds = null;
        boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] skey = SerializeUtil.serialize(key);
			byte[] svalue = SerializeUtil.serialize(value);
			jds.set(skey, svalue);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
	}
	/**
	 * 过期时间的
	 * @param key
	 * @param value
	 * @param timer (秒)
	 */
	public static void setex(Object key, Object value, int timer) {
		Jedis jds = null;
        boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] skey = SerializeUtil.serialize(key);
			byte[] svalue = SerializeUtil.serialize(value);
			jds.setex(skey, timer, svalue);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
		
	}
	/**
	 * 
	 * @param <T>
	 * @param mapkey map
	 * @param key	 map里的key
	 * @param requiredType value的泛型类型
	 * @return
	 */
	public static <T> T getVByMap(String mapkey,String key , Class<T> requiredType){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] mkey = SerializeUtil.serialize(mapkey);
			byte[] skey = SerializeUtil.serialize(key);
			List<byte[]> result = jds.hmget(mkey, skey);
			if(null != result && result.size() > 0 ){
				byte[] x = result.get(0);
				T resultObj = SerializeUtil.deserialize(x, requiredType);
				return resultObj;
			}
			
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return null;
	}
	/**
	 * 
	 * @param mapkey map
	 * @param key	 map里的key
	 * @param value   map里的value
	 */
	public static void setVByMap(String mapkey,String key ,Object value){
		Jedis jds = null;
        boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] mkey = SerializeUtil.serialize(mapkey);
			byte[] skey = SerializeUtil.serialize(key);
			byte[] svalue = SerializeUtil.serialize(value);
			jds.hset(mkey, skey,svalue);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
		
	}
	/**
	 * 删除Map里的值
	 * @param mapKey
	 * @param dkey
	 * @return
	 */
	public static Object delByMapKey(String mapKey ,String...dkey){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[][] dx = new byte[dkey.length][];
			for (int i = 0; i < dkey.length; i++) {
				dx[i] = SerializeUtil.serialize(dkey[i]);
			}
			byte[] mkey = SerializeUtil.serialize(mapKey);
			Long result = jds.hdel(mkey, dx);
			return result;
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return new Long(0);
	}
	
	/**
	 * 往redis里取set整个集合
	 * 
	 * @param <T>
	 * @param setKey
	 * @param requiredType
	 * @return
	 */
	public static <T> Set<T> getVByList(String setKey,Class<T> requiredType){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] lkey = SerializeUtil.serialize(setKey);
			Set<T> set = new TreeSet<T>();
			Set<byte[]> xx = jds.smembers(lkey);
			for (byte[] bs : xx) {
				T t = SerializeUtil.deserialize(bs, requiredType);
				set.add(t);
			}
			return set;
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return null;
	}
	/**
	 * 获取Set长度
	 * @param setKey
	 * @return
	 */
	public static Long getLenBySet(String setKey){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			Long result = jds.scard(setKey);
			return result;
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return null;
	}
	/**
	 * 删除Set
	 * @param dkey
	 * @return
	 */
	public static Long delSetByKey(String key,String...dkey){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			Long result = 0L;
			if(null == dkey){
				result = jds.srem(key);
			}else{
				result = jds.del(key);
			}
			return result;
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return new Long(0);
	}
	/**
	 * 随机 Set 中的一个值
	 * @param key
	 * @return
	 */
	public static String srandmember(String key){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			String result = jds.srandmember(key);
			return result;
		} catch (Exception e){ 
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return null;
	}
	/**
	 * 往redis里存Set
	 * @param setKey
	 * @param value
	 */
	public static void setVBySet(String setKey,String value){
		Jedis jds = null;
        boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			jds.sadd(setKey, value);
		} catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
	}
	/**
	 * 取set 
	 * @param key
	 * @return
	 */
	public static Set<String> getSetByKey(String key){
		Jedis jds = null;
        boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			Set<String> result = jds.smembers(key);
			return result;
		} catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;
		 
	}
	
	
	/**
	 * 往redis里存List
	 * @param listKey
	 * @param value
	 */
	public static void setVByList(String listKey,Object value){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] lkey = SerializeUtil.serialize(listKey);
			byte[] svalue = SerializeUtil.serialize(value);
			jds.rpush(lkey, svalue);
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
	}
	/**
	 * 往redis里取list
	 * 
	 * @param <T>
	 * @param listKey
	 * @param start
	 * @param end
	 * @param requiredType
	 * @return
	 */
	public static <T> List<T> getVByList(String listKey,int start,int end,Class<T> requiredType){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] lkey = SerializeUtil.serialize(listKey);
			List<T> list = new ArrayList<T>();
			List<byte[]> xx = jds.lrange(lkey,start,end);
			for (byte[] bs : xx) {
				T t = SerializeUtil.deserialize(bs, requiredType);
				list.add(t);
			}
			return list;
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return null;
	}
	/**
	 * 获取list长度
	 * @param listKey
	 * @return
	 */
	public static Long getLenByList(String listKey){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] lkey = SerializeUtil.serialize(listKey);
			Long result = jds.llen(lkey);
			return result;
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return null;
	}
	/**
	 * 删除
	 * @param dkey
	 * @return
	 */
	public static Long delByKey(String...dkey){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[][] dx = new byte[dkey.length][];
			for (int i = 0; i < dkey.length; i++) {
				dx[i] = SerializeUtil.serialize(dkey[i]);
			}
			Long result = jds.del(dx);
			return result;
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return new Long(0);
	}
	/**
	 * 判断是否存在
	 * @param existskey
	 * @return
	 */
	public static boolean exists(String existskey){
		Jedis jds = null;
		boolean isBroken = false;
		try {
			jds = jedisPool.getResource();
			jds.select(0);
			byte[] lkey = SerializeUtil.serialize(existskey);
			return jds.exists(lkey);
		} catch (Exception e) {
			isBroken = true;
			e.printStackTrace();
		} finally {
			returnResource(jds, isBroken);
		}
		return false;
	}
	/**
	 * 释放
	 * @param jedis
	 * @param isBroken
	 */
	public static void returnResource(Jedis jedis, boolean isBroken) {
        if (jedis == null)
            return;
            jedis.close();
	 }
}

 

package com.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import net.sf.json.JSONObject;

public class SerializeUtil {
	static final Class<?> CLAZZ = SerializeUtil.class;
	
    public static byte[] serialize(Object value) {
        if (value == null) { 
            throw new NullPointerException("Can't serialize null");
        }
        byte[] rv = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream os = null;
        try {
            bos = new ByteArrayOutputStream();
            os = new ObjectOutputStream(bos);
            os.writeObject(value);
            os.close();
            bos.close();
            rv = bos.toByteArray();
        } catch (Exception e) {
        	LoggerUtils.fmtError(CLAZZ,e, "serialize error %s", JSONObject.fromObject(value));
        } finally {
            close(os);
            close(bos);
        }
        return rv;
    }

    
	public static Object deserialize(byte[] in) {
        return deserialize(in, Object.class);
    }

    public static <T> T deserialize(byte[] in, Class<T>...requiredType) {
        Object rv = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            if (in != null) {
                bis = new ByteArrayInputStream(in);
                is = new ObjectInputStream(bis);
                rv = is.readObject();
            }
        } catch (Exception e) {
        	 LoggerUtils.fmtError(CLAZZ,e, "serialize error %s", in);
        } finally {
            close(is);
            close(bis);
        }
        return (T) rv;
    }

    private static void close(Closeable closeable) {
        if (closeable != null)
            try {
                closeable.close();
            } catch (IOException e) {
            	 LoggerUtils.fmtError(CLAZZ, "close stream error");
            }
    }

}

 

1
0
分享到:
评论

相关推荐

    自己在用的封装Jedis工具

    由于自己的redisTemplate出现不明原因用不了了,网上找了好几天也没找到一个比较好的工具, 所以自己整合了几份,并且做了相关优化, 现在用着比较顺手,从配置文件中读取相关设置, 用的时候直接调setString和getString就...

    JAVA整合JEDIS操作访问Redis的工具类

    JAVA整合JEDIS操作访问Redis的工具类,可以拿去直接用。里面包括REDIS连接池的处理,增删改查REDIS数据的封装,支持MAP/LIST/STRING等多种类型的存取

    JedisUtils.java

    一个Jedis的工具类,需要Spring Boot环境,依赖Redis和Jedis,更简便的操作Redis,封装重复的获取Jedis实例和关闭Jedis实例的代码。

    RedisUtils redis工具类

    由于JedisPool在使用完成后不会自动释放连接,所以我们对Jedis所有的API进行了封装,可以自动释放连接。

    spring-data-projects:测试SpringData整合其他工具的项目

    SpringData提供了针对数据库(包括SQL和NOSQL)的整合方案,对Hibernate JPA、Jedis等工具的api进行高级的封装,为我们提供简单方便地操作接口。 Spring Data JPA Spring Data提供了针对数据库(包括SQL和NOSQL)的...

    StringRedisUtil.java

    Redis工具类,使用了jedis客户端,对redis进行了封装, 包括: 1)使用了redispool获取连接;以及连接的回收; 2)常用五种数据结构的常用操作封装;

    Hotchpotch:大杂烩,工作中经常用到的工具等等

    Hotchpotch大杂烩,工作中经常用到的工具等等common目前...image剪切图片使用的工具类统一配置用于统一配置spring文件rocket-mq用于处理rocketmq消息堆积exceptionExceptionPicker工具类:用于从异常堆栈中,找出特定的

    Java秒杀系统方案优化高性能高并发学习实战源代码以及笔记..zip

    继承redis, 使用Jedis操作redis数据, 封装了统一的缓存key. 第2章-实现用户登录以及分布式session功能 学习了自己通过 cookie 实现分布式session, 不使用spring boot默认提供的 知识点 数据库设计 明文密码两次md5...

    基于SpringBoot+Shiro+Redis+Jwt+Thymeleaf+MyBatis 开发的后台用户、角色+源代码+文档

    * 优化日期时间工具类,使用Instant、LocalDateTime、LocalDate实现线性安全 * 修复Java开发规约中级警告及部分低级警告 * 增加debug日志输出开关 ###更新日期2018-12-28 * 项目增加健康检查暴露配置 * 根据JAVA...

    t淘淘商城项目 商城项目 视频和源码教程 详细

    |--taotao-common --- 通用组件、工具类 |--taotao-manage -- 后台系统  |--com.taotao.manage.web  |--com.taotao.manage.service  |--com.taotao.manage.mapper  |--com.taotao.manage.pojo 3.4. 创建...

    Eclipse开发分布式商城系统+完整视频代码及文档

    │ 09.FastDFS工具类的使用.avi │ 10.图片上传过程分析.avi │ 11.图片上传Service.avi │ 12.图片上传完成.avi │ 13.解决火狐兼容性问题.avi │ 14.spring的父子容器.avi │ 淘淘商城第三天笔记.docx │ ├─04....

Global site tag (gtag.js) - Google Analytics