Redis工具类(旧版本)
import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;/** * Created by qhong on 2018/6/5 17:08 **/@Componentpublic class RedisUtil { @Autowired private RedisTemplateredisTemplate; //=============================common============================ /** * 指定缓存失效时间 * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key,long time){ try { if(time>0){ redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据key 获取过期时间 * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key){ return redisTemplate.getExpire(key,TimeUnit.SECONDS); } /** * 判断key是否存在 * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key){ try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除缓存 * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(String ... key){ if(key!=null&&key.length>0){ if(key.length==1){ redisTemplate.delete(key[0]); }else{ redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } //============================String============================= /** * 普通缓存获取 * @param key 键 * @return 值 */ public Object get(String key){ return key==null?null:redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key,Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存放入并设置时间 * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(String key,Object value,long time){ try { if(time>0){ redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); }else{ set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 递增 * @param key 键 * @param by 要增加几(大于0) * @return */ public long incr(String key, long delta){ if(delta<0){ throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * @param key 键 * @param by 要减少几(小于0) * @return */ public long decr(String key, long delta){ if(delta<0){ throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } //================================Map================================= /** * HashGet * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key,String item){ return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * @param key 键 * @return 对应的多个键值 */ public Map
新版:
import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.ListOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.SetOperations;import org.springframework.data.redis.core.ValueOperations;import org.springframework.data.redis.core.ZSetOperations;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;/** * Created by qhong on 2018/6/5 17:08 **/@Componentpublic class RedisUtil { @Autowired private RedisTemplateredisTemplate; @Autowired private ValueOperations valueOperations; @Autowired private HashOperations hashOperations; @Autowired private ListOperations listOperations; @Autowired private SetOperations setOperations; @Autowired private ZSetOperations zSetOperations; //=============================common============================ /** * 指定缓存失效时间 * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key,long time){ try { if(time>0){ redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据key 获取过期时间 * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key){ return redisTemplate.getExpire(key,TimeUnit.SECONDS); } /** * 判断key是否存在 * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key){ try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除缓存 * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(String ... key){ if(key!=null&&key.length>0){ if(key.length==1){ redisTemplate.delete(key[0]); }else{ redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } //============================String============================= /** * 普通缓存获取 * @param key 键 * @return 值 */ public Object get(String key){ return key==null?null:valueOperations.get(key); } /** * 普通缓存放入 * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key,Object value) { try { valueOperations.set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存放入并设置时间 * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(String key,Object value,long time){ try { if(time>0){ valueOperations.set(key, value, time, TimeUnit.SECONDS); }else{ set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 递增 * @param key 键 * @param by 要增加几(大于0) * @return */ public long incr(String key, long delta){ if(delta<0){ throw new RuntimeException("递增因子必须大于0"); } return valueOperations.increment(key, delta); } /** * 递减 * @param key 键 * @param by 要减少几(小于0) * @return */ public long decr(String key, long delta){ if(delta<0){ throw new RuntimeException("递减因子必须大于0"); } return valueOperations.increment(key, -delta); } //================================Map================================= /** * HashGet * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key,String item){ return hashOperations.get(key, item); } /** * 获取hashKey对应的所有键值 * @param key 键 * @return 对应的多个键值 */ public Map hmget(String key){ return hashOperations.entries(key); } /** * HashSet * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map map){ try { hashOperations.putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map map, long time){ try { hashOperations.putAll(key, map); if(time>0){ expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * @param key 键 * @param item 项 * @param value 值 * @return true 成功 false失败 */ public boolean hset(String key,String item,Object value) { try { hashOperations.put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 向一张hash表中放入数据,如果不存在将创建 * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 * @return true 成功 false失败 */ public boolean hset(String key,String item,Object value,long time) { try { hashOperations.put(key, item, value); if(time>0){ expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除hash表中的值 * @param key 键 不能为null * @param item 项 可以使多个 不能为null */ public void hdel(String key, Object... item){ hashOperations.delete(key,item); } /** * 判断hash表中是否有该项的值 * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item){ return hashOperations.hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item,double by){ return hashOperations.increment(key, item, by); } /** * hash递减 * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item,double by){ return hashOperations.increment(key, item,-by); } //============================set============================= /** * 根据key获取Set中的所有值 * @param key 键 * @return */ public Set sGet(String key){ try { return setOperations.members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 根据value从一个set中查询,是否存在 * @param key 键 * @param value 值 * @return true 存在 false不存在 */ public boolean sHasKey(String key,Object value){ try { return setOperations.isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将数据放入set缓存 * @param key 键 * @param values 值 可以是多个 * @return 成功个数 */ public long sSet(String key, Object...values) { try { return setOperations.add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 将set数据放入缓存 * @param key 键 * @param time 时间(秒) * @param values 值 可以是多个 * @return 成功个数 */ public long sSetAndTime(String key,long time,Object...values) { try { Long count = setOperations.add(key, values); if(time>0) expire(key, time); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 获取set缓存的长度 * @param key 键 * @return */ public long sGetSetSize(String key){ try { return setOperations.size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 移除值为value的 * @param key 键 * @param values 值 可以是多个 * @return 移除的个数 */ public long setRemove(String key, Object ...values) { try { Long count = setOperations.remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } //===============================list================================= /** * 获取list缓存的内容 * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return */ public List lGet(String key, long start, long end){ try { return listOperations.range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的所有内容 * @param key * @return */ public List lGetAll(String key){ return lGet(key,0,-1); } /** * 获取list缓存的长度 * @param key 键 * @return */ public long lGetListSize(String key){ try { return listOperations.size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * 通过索引 获取list中的值 * @param key 键 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推 * @return */ public Object lGetIndex(String key,long index){ try { return listOperations.index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, Object value) { try { listOperations.rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, Object value, long time) { try { listOperations.rightPush(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, List value) { try { listOperations.rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @param time 时间(秒) * @return */ public boolean lSet(String key, List value, long time) { try { listOperations.rightPushAll(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据索引修改list中的某条数据 * @param key 键 * @param index 索引 * @param value 值 * @return */ public boolean lUpdateIndex(String key, long index,Object value) { try { listOperations.set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 移除N个值为value * @param key 键 * @param count 移除多少个 * @param value 值 * @return 移除的个数 */ public long lRemove(String key,long count,Object value) { try { Long remove = listOperations.remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } }}
RedisConfig:
import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.ListOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.SetOperations;import org.springframework.data.redis.core.ValueOperations;import org.springframework.data.redis.core.ZSetOperations;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;/** * Created by qhong on 2018/6/5 17:31 **/@Configurationpublic class RedisConfig { @Autowired private RedisConnectionFactory factory; @Bean public RedisTemplateredisTemplate() { Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisTemplate template = new RedisTemplate (); template.setConnectionFactory(factory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.setDefaultSerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } @Bean public HashOperations hashOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForHash(); } @Bean public ValueOperations valueOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForValue(); } @Bean public ListOperations listOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForList(); } @Bean public SetOperations setOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForSet(); } @Bean public ZSetOperations zSetOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForZSet(); }}
application.properties:
# REDIS (RedisProperties)# Redis数据库索引(默认为0)spring.redis.database=0# Redis服务器地址spring.redis.host=127.0.0.1# Redis服务器连接端口spring.redis.port=6379# Redis服务器连接密码(默认为空)spring.redis.password=# 连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=8# 连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1# 连接池中的最大空闲连接spring.redis.pool.max-idle=8# 连接池中的最小空闲连接spring.redis.pool.min-idle=0# 连接超时时间(毫秒)spring.redis.timeout=0
上面的例子还是有问题的
主要是RedisTemplate序列化问题
特别是在使用数组操作的时候
仅供参考学习
当然也可以使用其他方式解决这些序列化问题 ,就是转换成字符串,但是不喜欢
/** * Created by qhong on 2018/6/7 10:25 **/public class RedisCacheUtil { private static RedisTemplateredisTemplate; public void setRedisTemplate(RedisTemplate redisTemp) { redisTemplate = redisTemp; } /* ----------- common --------- */ public static Collection keys(String pattern) { return redisTemplate.keys(pattern); } public static void delete(String key) { redisTemplate.delete(key); } public static void delete(Collection key) { redisTemplate.delete(key); } /* ----------- string --------- */ public static T get(String key, Class clazz) { String value = redisTemplate.opsForValue().get(key); return parseJson(value, clazz); } public static List mget(Collection keys, Class clazz) { List values = redisTemplate.opsForValue().multiGet(keys); return parseJsonList(values, clazz); } public static void set(String key, T obj, Long timeout, TimeUnit unit) { if (obj == null) { return; } String value = toJson(obj); if (timeout != null) { redisTemplate.opsForValue().set(key, value, timeout, unit); } else { redisTemplate.opsForValue().set(key, value); } } public static T getAndSet(String key, T obj, Class clazz) { if (obj == null) { return get(key, clazz); } String value = redisTemplate.opsForValue().getAndSet(key, toJson(obj)); return parseJson(value, clazz); } public static int decrement(String key, int delta) { Long value = redisTemplate.opsForValue().increment(key, -delta); return value.intValue(); } public static int increment(String key, int delta) { Long value = redisTemplate.opsForValue().increment(key, delta); return value.intValue(); } /* ----------- list --------- */ public static int size(String key) { return redisTemplate.opsForList().size(key).intValue(); } public static List range(String key, long start, long end, Class clazz) { List list = redisTemplate.opsForList().range(key, start, end); return parseJsonList(list, clazz); } public static void rightPushAll(String key, Collection values, Long timeout, TimeUnit unit) { if (values == null || values.isEmpty()) { return; } redisTemplate.opsForList().rightPushAll(key, toJsonList(values)); if (timeout != null) { redisTemplate.expire(key, timeout, unit); } } public static void leftPush(String key, T obj) { if (obj == null) { return; } redisTemplate.opsForList().leftPush(key, toJson(obj)); } public static T leftPop(String key, Class clazz) { String value = redisTemplate.opsForList().leftPop(key); return parseJson(value, clazz); } public static void remove(String key, int count, Object obj) { if (obj == null) { return; } redisTemplate.opsForList().remove(key, count, toJson(obj)); } /* ----------- zset --------- */ public static int zcard(String key) { return redisTemplate.opsForZSet().zCard(key).intValue(); } public static List zrange(String key, long start, long end, Class clazz) { Set set = redisTemplate.opsForZSet().range(key, start, end); return parseJsonList(setToList(set), clazz); } private static List setToList(Set set) { if (set == null) { return null; } return new ArrayList (set); } public static void zadd(String key, Object obj, double score) { if (obj == null) { return; } redisTemplate.opsForZSet().add(key, toJson(obj), score); } public static void zaddAll(String key, List > tupleList, Long timeout, TimeUnit unit) { if (tupleList == null || tupleList.isEmpty()) { return; } Set > tupleSet = toTupleSet(tupleList); redisTemplate.opsForZSet().add(key, tupleSet); if (timeout != null) { redisTemplate.expire(key, timeout, unit); } } private static Set > toTupleSet(List > tupleList) { Set > tupleSet = new LinkedHashSet >(); for (TypedTuple t : tupleList) { tupleSet.add(new DefaultTypedTuple (toJson(t.getValue()), t.getScore())); } return tupleSet; } public static void zrem(String key, Object obj) { if (obj == null) { return; } redisTemplate.opsForZSet().remove(key, toJson(obj)); } public static void unionStore(String destKey, Collection keys, Long timeout, TimeUnit unit) { if (keys == null || keys.isEmpty()) { return; } Object[] keyArr = keys.toArray(); String key = (String) keyArr[0]; Collection otherKeys = new ArrayList (keys.size() - 1); for (int i = 1; i < keyArr.length; i++) { otherKeys.add((String) keyArr[i]); } redisTemplate.opsForZSet().unionAndStore(key, otherKeys, destKey); if (timeout != null) { redisTemplate.expire(destKey, timeout, unit); } } /* ----------- tool methods --------- */ public static String toJson(Object obj) { return JSON.toJSONString(obj, SerializerFeature.SortField); } public static T parseJson(String json, Class clazz) { return JSON.parseObject(json, clazz); } public static List toJsonList(Collection values) { if (values == null) { return null; } List result = new ArrayList (); for (Object obj : values) { result.add(toJson(obj)); } return result; } public static List parseJsonList(List list, Class clazz) { if (list == null) { return null; } List result = new ArrayList (); for (String s : list) { result.add(parseJson(s, clazz)); } return result; }}
又一版本:
@Componentpublic class RedisCache { @Autowired private RedisTemplateredisTemplate; public RedisCache() { } public RedisTemplate getRedisTemplate() { return this.redisTemplate; } public void setRedisTemplate(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public Object get(Object key) { final String keyf = key.toString(); Object object = null; object = this.redisTemplate.execute(new RedisCallback () { public Object doInRedis(RedisConnection connection) throws DataAccessException { byte[] key = keyf.getBytes(); byte[] value = connection.get(key); return value == null ? null : RedisCache.this.toObject(value); } }); return object; } public void put(Object key, final Object value, final long liveTime) { final String keyf = key.toString(); this.redisTemplate.execute(new RedisCallback () { public Long doInRedis(RedisConnection connection) throws DataAccessException { byte[] keyb = keyf.getBytes(); byte[] valueb = RedisCache.this.toByteArray(value); connection.set(keyb, valueb); if (liveTime > 0L) { connection.expire(keyb, liveTime); } return 1L; } }); } private byte[] toByteArray(Object obj) { byte[] bytes = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); bytes = bos.toByteArray(); oos.close(); bos.close(); } catch (IOException var5) { var5.printStackTrace(); } return bytes; } private Object toObject(byte[] bytes) { Object obj = null; try { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); obj = ois.readObject(); ois.close(); bis.close(); } catch (IOException var5) { var5.printStackTrace(); } catch (ClassNotFoundException var6) { var6.printStackTrace(); } return obj; } public void del(Object key) { final String keyf = key.toString(); this.redisTemplate.execute(new RedisCallback () { public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.del(new byte[][]{keyf.getBytes()}); } }); } public void exprie(Object key, final long liveTime) { final String keyf = key.toString(); this.redisTemplate.execute(new RedisCallback () { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { return connection.expire(keyf.getBytes(), liveTime); } }); } public Boolean exist(Object key) { final String keyf = key.toString(); return (Boolean)this.redisTemplate.execute(new RedisCallback () { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { return connection.exists(keyf.getBytes()); } }); } public void clear() { this.redisTemplate.execute(new RedisCallback () { public String doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); return "ok"; } }); } public Long incr(Object key) { final String keyf = key.toString(); return (Long)this.redisTemplate.execute(new RedisCallback () { public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.incr(keyf.getBytes()); } }); } public Long decr(Object key) { final String keyf = key.toString(); return (Long)this.redisTemplate.execute(new RedisCallback () { public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.decr(keyf.getBytes()); } }); } public Set keys(String key) { Set keys = this.redisTemplate.keys(key); return keys; }}