216396734 交流群
JedisUtils.java package com.youquhd.common.redis; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.youquhd.common.utils.StringUtils; import com.youquhd.modules.sys.entity.User; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.exceptions.JedisException; /** * Jedis常用功能 * @author liucx * @email [email protected] */ public class JedisUtils { public static final String PK="pk_"; private static Logger logger = LoggerFactory.getLogger(JedisUtils.class); private static JedisPool jedisPool =new JedisPool("192.168.3.250");//SpringContextHolder.getBean(JedisPool.class); /** * 设置分布式事物锁 * 1、返回0表示锁已经存在,返回1表示获得锁成功 * @param key * @param cacheSeconds * @return */ public static long setNx(String key, int cacheSeconds) { long value = 0L; Jedis jedis = null; try { jedis = getResource(); value = jedis.setnx(key, "1"); if(cacheSeconds>0) { jedis.expire(key, cacheSeconds); //避免死锁 } } catch (Exception e) { logger.debug("setNx {} = {}", key, cacheSeconds, e); } finally { returnResource(jedis); } return value; } /** * 获取自增id * 该方法单机每秒并发在1100左右 * @param key 键 * @return 值 */ public static long incrementAndGet(String key) { long value = 0L; Jedis jedis = null; try { jedis = getResource(); value=jedis.incr("increment_"+key); } catch (Exception e) { logger.debug("incrementAndGet {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 根据key获取缓存 * @param key 键 * @return 值 */ public static String get(String key) { String value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { value = jedis.get(key); value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null; logger.debug("get {} = {}", key, value); } } catch (Exception e) { logger.warn("get {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 设置缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String set(String key, String value, int cacheSeconds) { String result = null; Jedis jedis = null; try { jedis = getResource(); result = jedis.set(key, value); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("set {} = {}", key, value); } catch (Exception e) { logger.warn("set {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 更新缓存时间 * @param key key值 * @param sessionSeconds 更新多长时间 */ public static void expire(String key,int sessionSeconds){ Jedis jedis = null; try { jedis = getResource(); if (sessionSeconds != 0) { jedis.expire(key, sessionSeconds); } } catch (Exception e) { logger.warn("set {} = {}", key, sessionSeconds, e); } finally { returnResource(jedis); } } /** * 设置缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String setObject(String key, Object value, int cacheSeconds) { String result = null; Jedis jedis = null; try { jedis = getResource(); result = jedis.set(getBytesKey(key), toBytes(value)); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObject {} = {}", key, value); } catch (Exception e) { logger.warn("setObject {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 获取缓存 * @param key 键 * @return 值 */ public static Object getObject(String key) { Object value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { value = toObject(jedis.get(getBytesKey(key))); logger.debug("getObject {} = {}", key, value); } } catch (Exception e) { logger.warn("getObject {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 设置List缓存,如果该key值原来就 存在,覆盖原来的 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setList(String key, List value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.rpush(key, (String[])value.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setList {} = {}", key, value); } catch (Exception e) { logger.warn("setList {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 获取List缓存 * @param key 键 * @return 值 */ public static List getList(String key) { List value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { value = jedis.lrange(key, 0, -1); logger.debug("getList {} = {}", key, value); } } catch (Exception e) { logger.warn("getList {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 向List缓存中添加值,在list后面追加 * @param key 键 * @param value 值 * @return */ public static long listAdd(String key, String... value) { long result = 0; Jedis jedis = null; try { jedis = getResource(); result = jedis.rpush(key, value); logger.debug("listAdd {} = {}", key, value); } catch (Exception e) { logger.warn("listAdd {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 设置List缓存,如果该key值已经存在,覆盖原来的值 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setObjectList(String key, List> value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(ObjectUtils.serialize(key))) { jedis.del(ObjectUtils.serialize(key)); } for(int i=0;ijedis.rpush(ObjectUtils.serialize(key), ObjectUtils.serialize(value.get(i))); } if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObjectList {} = {}", key, value); } catch (Exception e) { logger.warn("setObjectList {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向List缓存中添加值,在原来list的后面增加 * @param key 键 * @param value 值 * @return */ public static long listObjectAdd(String key, Object... value) { long result = 0; Jedis jedis = null; try { jedis = getResource(); for (Object o : value){ jedis.rpush(ObjectUtils.serialize(key), ObjectUtils.serialize(o)); } logger.debug("listObjectAdd {} = {}", key, value); } catch (Exception e) { logger.warn("listObjectAdd {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 获取List缓存 start传0 end传-1查询全部 * @param key * @param start 列表开始值 从0开始计数 ,(可以是负数,当为负数的时候值列表结尾的偏移量,如-2知道从倒数第二条开始) * @param end 取列表结尾的数 * @return */ public static List> getObjectList(String key,int start,int end) { List value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(ObjectUtils.serialize(key))) { List list = jedis.lrange(ObjectUtils.serialize(key), start, end); value = Lists.newArrayList(); for (byte[] bs : list){ value.add(toObject(bs)); } logger.debug("getObjectList {} = {}", key, value); } } catch (Exception e) { logger.warn("getObjectList {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 获取缓存 * @param key 键 * @return 值 */ public static Set getSet(String key) { Set value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { value = jedis.smembers(key); logger.debug("getSet {} = {}", key, value); } } catch (Exception e) { logger.warn("getSet {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 获取缓存 * @param key 键 * @return 值 */ public static Set getObjectSet(String key) { Set value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { value = Sets.newHashSet(); Set set = jedis.smembers(getBytesKey(key)); for (byte[] bs : set){ value.add(toObject(bs)); } logger.debug("getObjectSet {} = {}", key, value); } } catch (Exception e) { logger.warn("getObjectSet {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 设置Set缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setSet(String key, Set value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)) { jedis.del(key); } result = jedis.sadd(key, (String[])value.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setSet {} = {}", key, value); } catch (Exception e) { logger.warn("setSet {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 设置Set缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static long setObjectSet(String key, Set value, int cacheSeconds) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { jedis.del(key); } Set set = Sets.newHashSet(); for (Object o : value){ set.add(toBytes(o)); } result = jedis.sadd(getBytesKey(key), (byte[][])set.toArray()); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObjectSet {} = {}", key, value); } catch (Exception e) { logger.warn("setObjectSet {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向Set缓存中添加值 * @param key 键 * @param value 值 * @return */ public static long setSetAdd(String key, String... value) { long result = 0; Jedis jedis = null; try { jedis = getResource(); result = jedis.sadd(key, value); logger.debug("setSetAdd {} = {}", key, value); } catch (Exception e) { logger.warn("setSetAdd {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向Set缓存中添加值 * @param key 键 * @param value 值 * @return */ public static long setSetObjectAdd(String key, Object... value) { long result = 0; Jedis jedis = null; try { jedis = getResource(); Set set = Sets.newHashSet(); for (Object o : value){ set.add(toBytes(o)); } result = jedis.rpush(getBytesKey(key), (byte[][])set.toArray()); logger.debug("setSetObjectAdd {} = {}", key, value); } catch (Exception e) { logger.warn("setSetObjectAdd {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 获取Map缓存 * @param key 键 * @return 值 */ public static Map getObjectMap(String key) { Map value = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { value = Maps.newHashMap(); Map map = jedis.hgetAll(getBytesKey(key)); for (Map.Entry e : map.entrySet()){ value.put(StringUtils.toString(e.getKey()), toObject(e.getValue())); } logger.debug("getObjectMap {} = {}", key, value); } } catch (Exception e) { logger.warn("getObjectMap {} = {}", key, value, e); } finally { returnResource(jedis); } return value; } /** * 设置Map缓存 * @param key 键 * @param value 值 * @param cacheSeconds 超时时间,0为不超时 * @return */ public static String setMap(String key, Map value, int cacheSeconds) { String result = null; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))) { jedis.del(key); } Map map = Maps.newHashMap(); for (Map.Entry e : value.entrySet()){ map.put(getBytesKey(e.getKey()), toBytes(e.getValue())); } result = jedis.hmset(getBytesKey(key), (Map)map); if (cacheSeconds != 0) { jedis.expire(key, cacheSeconds); } logger.debug("setObjectMap {} = {}", key, value); } catch (Exception e) { logger.warn("setObjectMap {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 向Map缓存中添加值 * @param key 键 * @param value 值 * @return */ public static String mapPut(String key, Map value) { String result = null; Jedis jedis = null; try { jedis = getResource(); Map map = Maps.newHashMap(); for (Map.Entry e : value.entrySet()){ map.put(getBytesKey(e.getKey()), toBytes(e.getValue())); } result = jedis.hmset(getBytesKey(key), (Map)map); logger.debug("mapObjectPut {} = {}", key, value); } catch (Exception e) { logger.warn("mapObjectPut {} = {}", key, value, e); } finally { returnResource(jedis); } return result; } /** * 移除Map缓存中的值 * @param key 键 * @param value 值 * @return */ public static long mapRemove(String key, String mapKey) { long result = 0; Jedis jedis = null; try { jedis = getResource(); result = jedis.hdel(getBytesKey(key), getBytesKey(mapKey)); logger.debug("mapObjectRemove {} {}", key, mapKey); } catch (Exception e) { logger.warn("mapObjectRemove {} {}", key, mapKey, e); } finally { returnResource(jedis); } return result; } /** * 判断Map缓存中的Key是否存在 * @param key 键 * @param value 值 * @return */ public static boolean mapExists(String key, String mapKey) { boolean result = false; Jedis jedis = null; try { jedis = getResource(); result = jedis.hexists(getBytesKey(key), getBytesKey(mapKey)); logger.debug("mapObjectExists {} {}", key, mapKey); } catch (Exception e) { logger.warn("mapObjectExists {} {}", key, mapKey, e); } finally { returnResource(jedis); } return result; } /** * 删除缓存 * @param key 键 * @return */ public static long del(String key) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(key)){ result = jedis.del(key); logger.debug("del {}", key); }else{ logger.debug("del {} not exists", key); } } catch (Exception e) { logger.warn("del {}", key, e); } finally { returnResource(jedis); } return result; } /** * 删除缓存 * @param key 键 * @return */ public static long delObject(String key) { long result = 0; Jedis jedis = null; try { jedis = getResource(); if (jedis.exists(getBytesKey(key))){ result = jedis.del(getBytesKey(key)); logger.debug("delObject {}", key); }else{ logger.debug("delObject {} not exists", key); } } catch (Exception e) { logger.warn("delObject {}", key, e); } finally { returnResource(jedis); } return result; } /** * 缓存是否存在 * @param key 键 * @return */ public static boolean exists(String key) { boolean result = false; Jedis jedis = null; try { jedis = getResource(); result = jedis.exists(key); logger.debug("exists {}", key); } catch (Exception e) { logger.warn("exists {}", key, e); } finally { returnResource(jedis); } return result; } /** * 缓存是否存在 * @param key 键 * @return */ public static boolean existsObject(String key) { boolean result = false; Jedis jedis = null; try { jedis = getResource(); result = jedis.exists(getBytesKey(key)); logger.debug("existsObject {}", key); } catch (Exception e) { logger.warn("existsObject {}", key, e); } finally { returnResource(jedis); } return result; } /** * 获取资源 * @return * @throws JedisException */ public static Jedis getResource() throws JedisException { Jedis jedis = null; try { jedis = jedisPool.getResource(); // logger.debug("getResource.", jedis); } catch (JedisException e) { logger.warn("getResource.", e); returnBrokenResource(jedis); throw e; } return jedis; } /** * 归还资源 * @param jedis * @param isBroken */ public static void returnBrokenResource(Jedis jedis) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); } } /** * 释放资源 * @param jedis * @param isBroken */ public static void returnResource(Jedis jedis) { if (jedis != null) { jedisPool.returnResource(jedis); } } /** * 获取byte[]类型object * @param object * @return */ public static byte[] getBytesKey(Object object){ if(object instanceof String){ return StringUtils.getBytes((String)object); }else{ return ObjectUtils.serialize(object); } } /** * 获取byte[]类型Key * @param key * @return */ public static Object getObjectKey(byte[] key){ try{ return StringUtils.toString(key); }catch(UnsupportedOperationException uoe){ try{ return JedisUtils.toObject(key); }catch(UnsupportedOperationException uoe2){ uoe2.printStackTrace(); } } return null; } /** * Object转换byte[]类型 * @param key * @return */ public static byte[] toBytes(Object object){ return ObjectUtils.serialize(object); } /** * byte[]型转换Object * @param key * @return */ public static Object toObject(byte[] bytes){ return ObjectUtils.unserialize(bytes); } }
ObjectUtils.java package com.youquhd.common.redis; 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 java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; /** * @author liucx */ public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils { /** * 注解到对象复制,只复制能匹配上的方法。 * @param annotation * @param object */ public static void annotationToObject(Object annotation, Object object){ if (annotation != null){ Class> annotationClass = annotation.getClass(); Class> objectClass = object.getClass(); for (Method m : objectClass.getMethods()){ if (StringUtils.startsWith(m.getName(), "set")){ try { String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3)); Object obj = annotationClass.getMethod(s).invoke(annotation); if (obj != null && !"".equals(obj.toString())){ if (object == null){ object = objectClass.newInstance(); } m.invoke(object, obj); } } catch (Exception e) { // 忽略所有设置失败方法 } } } } } /** * 序列化对象 * @param object * @return */ public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { if (object != null){ if(object instanceof String){ return ((String) object).getBytes(); } baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); return baos.toByteArray(); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 反序列化对象 * @param bytes * @return */ public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { if (bytes != null && bytes.length > 0){ bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 序列化 list 集合 * * @param list * @return */ public static byte[] serializeList(List> list) { if (list==null||list.isEmpty()) { return null; } ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; byte[] bytes = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); for (Object obj : list) { oos.writeObject(obj); } bytes = baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { close(oos); close(baos); } return bytes; } /** * 反序列化 list 集合 * @param bytes * @return */ public static List> unserializeList(byte[] bytes) { if (bytes == null) { return null; } List list = new ArrayList(); ByteArrayInputStream bais = null; ObjectInputStream ois = null; try { // 反序列化 bais = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bais); while (bais.available() > 0) { Object obj = (Object) ois.readObject(); if (obj == null) { break; } list.add(obj); } } catch (Exception e) { e.printStackTrace(); } finally { close(bais); close(ois); } return list; } public static void close(Closeable closeable){ try { closeable.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }