-
2022-05-07 10:38:36
Redis工具类封装
使用redis也好几年了,总是拷贝来拷贝去的,这次干脆放在这把,每次来这拷贝,不用在工程里面找来找去了。
/** * Redis工具类 * @author Huangliniao * @since 2022-05-07 * @version 1.0 */ @Component public class RedisBean { @Resource private RedisTemplate<String, Object> redisTemplate; /** * 存放Object到指定的key * @param key * @param value * @return */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 存放Object到指定的key,并指定时效时间 * @param key * @param value * @param time 单位为秒 * @return */ 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; } } /** * 获取指定key的值 * @param key * @return */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 删除key * @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)); } } } /** * 指定key的过期时间 * @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 * @return 返回-1表示没有指定时效时间 */ 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 * @param delta * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * @param key * @param delta * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } }
备注:在启动工程的时候报了一个错误,日志如下:
Field redisTemplate in com.example.common.redis.RedisBean required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found.
将RedisTemplate的注解@Autowired改为@Resource后得已解决。
更多相关内容 -
Redis操作字符串工具类封装,Redis工具类封装
2019-06-07 01:02:09NULL 博文链接:https://fanshuyao.iteye.com/blog/2326221 -
SpringBoot Redis工具类封装
2019-06-18 19:50:53SpringBoot整合Redis的博客很多,...看了很多博客后,我成功的整合了,并写了个Redis操作工具类。特意在此记录一下,方便后续查阅。 一、Maven依赖 1、本文所采用的SpringBoot的版本如下 <parent> <...SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果。因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable)。看了很多博客后,我成功的整合了,并写了个Redis操作工具类。特意在此记录一下,方便后续查阅。
一、Maven依赖
1、本文所采用的SpringBoot的版本如下
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> </parent>
2、加入Redis相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
二、application.properties中加入redis相关配置
# Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=192.168.0.24 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=200 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=10 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=1000
三、写一个redis配置类
1、聊聊RedisTemplate的自动配置
其实现在就可以在代码中注入RedisTemplate,为啥可以直接注入呢?先看下源码吧。下图为 RedisAutoConfiguration类中的截图,为了防止图片失效,代码也贴上 。
代码如下:
@Configuration @ConditionalOnClass(RedisOperations.class) @EnableConfigurationProperties(RedisProperties.class) @Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class }) public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<Object, Object> redisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean @ConditionalOnMissingBean public StringRedisTemplate stringRedisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } }
通过源码可以看出,SpringBoot自动帮我们在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是<Object,Object>,写代码不方便,需要写好多类型转换的代码;我们需要一个泛型为<String,Object>形式的RedisTemplate。并且,这个RedisTemplate没有设置数据存在Redis时,key及value的序列化方式。
看到这个@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate对象了,这个自动配置的RedisTemplate不会实例化。因此我们可以直接自己写个配置类,配置RedisTemplate。
2、既然自动配置不好用,就重新配置一个RedisTemplate
package com.oal.microservice.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; 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.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * redis配置类 * @author zhangzhixiang * @date 2019年06月19日 * */ @Configuration public class RedisConfig { @Bean @SuppressWarnings("all") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(factory); 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); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
四、写一个Redis工具类
直接用RedisTemplate操作Redis,需要很多行代码,因此直接封装好一个RedisUtils,这样写代码更方便点。这个RedisUtils交给Spring容器实例化,使用时直接注解注入。
工具类代码如下:
package com.oal.microservice.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Redis工具类 * * @author zhangzhixiang * @date 2019年06月19日 */ @Component public final class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; // =============================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 delta 要增加几(大于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 delta 要减少几(小于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<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().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<String, Object> map, long time) { try { redisTemplate.opsForHash().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 { redisTemplate.opsForHash().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 { redisTemplate.opsForHash().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) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash递减 * * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================set============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 = redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 = redisTemplate.opsForSet().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<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().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 redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().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 { redisTemplate.opsForList().rightPush(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().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<Object> value, long time) { try { redisTemplate.opsForList().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 { redisTemplate.opsForList().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 = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } }
-
Redis工具类封装RedisUtils(两种)
2021-05-09 19:51:04RedisTemplate工具类1 本文参考:https://blog.it-follower.com/posts/2563248908.html SpringBoot项目集成Redis相当简单,只需要pom中加入对应依赖 <dependency> <groupId>org.springframework....RedisTemplate工具类1
本文参考:https://blog.it-follower.com/posts/2563248908.html
SpringBoot项目集成Redis相当简单,只需要pom中加入对应依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
yml中,配置好spring.redis.host,spring.redis.port即可。具体如何封装,直接上代码。
/** * Redis工具类,使用之前请确保RedisTemplate成功注入 * * @author ye17186 * @version 2019/2/22 10:48 */ public class RedisUtils { private RedisUtils() { } @SuppressWarnings("unchecked") private static RedisTemplate<String, Object> redisTemplate = SpringUtils .getBean("redisTemplate", RedisTemplate.class); /** * 设置有效时间 * * @param key Redis键 * @param timeout 超时时间 * @return true=设置成功;false=设置失败 */ public static boolean expire(final String key, final long timeout) { return expire(key, timeout, TimeUnit.SECONDS); } /** * 设置有效时间 * * @param key Redis键 * @param timeout 超时时间 * @param unit 时间单位 * @return true=设置成功;false=设置失败 */ public static boolean expire(final String key, final long timeout, final TimeUnit unit) { Boolean ret = redisTemplate.expire(key, timeout, unit); return ret != null && ret; } /** * 删除单个key * * @param key 键 * @return true=删除成功;false=删除失败 */ public static boolean del(final String key) { Boolean ret = redisTemplate.delete(key); return ret != null && ret; } /** * 删除多个key * * @param keys 键集合 * @return 成功删除的个数 */ public static long del(final Collection<String> keys) { Long ret = redisTemplate.delete(keys); return ret == null ? 0 : ret; } /** * 存入普通对象 * * @param key Redis键 * @param value 值 */ public static void set(final String key, final Object value) { redisTemplate.opsForValue().set(key, value, 1, TimeUnit.MINUTES); } // 存储普通对象操作 /** * 存入普通对象 * * @param key 键 * @param value 值 * @param timeout 有效期,单位秒 */ public static void set(final String key, final Object value, final long timeout) { redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS); } /** * 获取普通对象 * * @param key 键 * @return 对象 */ public static Object get(final String key) { return redisTemplate.opsForValue().get(key); } // 存储Hash操作 /** * 往Hash中存入数据 * * @param key Redis键 * @param hKey Hash键 * @param value 值 */ public static void hPut(final String key, final String hKey, final Object value) { redisTemplate.opsForHash().put(key, hKey, value); } /** * 往Hash中存入多个数据 * * @param key Redis键 * @param values Hash键值对 */ public static void hPutAll(final String key, final Map<String, Object> values) { redisTemplate.opsForHash().putAll(key, values); } /** * 获取Hash中的数据 * * @param key Redis键 * @param hKey Hash键 * @return Hash中的对象 */ public static Object hGet(final String key, final String hKey) { return redisTemplate.opsForHash().get(key, hKey); } /** * 获取多个Hash中的数据 * * @param key Redis键 * @param hKeys Hash键集合 * @return Hash对象集合 */ public static List<Object> hMultiGet(final String key, final Collection<Object> hKeys) { return redisTemplate.opsForHash().multiGet(key, hKeys); } // 存储Set相关操作 /** * 往Set中存入数据 * * @param key Redis键 * @param values 值 * @return 存入的个数 */ public static long sSet(final String key, final Object... values) { Long count = redisTemplate.opsForSet().add(key, values); return count == null ? 0 : count; } /** * 删除Set中的数据 * * @param key Redis键 * @param values 值 * @return 移除的个数 */ public static long sDel(final String key, final Object... values) { Long count = redisTemplate.opsForSet().remove(key, values); return count == null ? 0 : count; } // 存储List相关操作 /** * 往List中存入数据 * * @param key Redis键 * @param value 数据 * @return 存入的个数 */ public static long lPush(final String key, final Object value) { Long count = redisTemplate.opsForList().rightPush(key, value); return count == null ? 0 : count; } /** * 往List中存入多个数据 * * @param key Redis键 * @param values 多个数据 * @return 存入的个数 */ public static long lPushAll(final String key, final Collection<Object> values) { Long count = redisTemplate.opsForList().rightPushAll(key, values); return count == null ? 0 : count; } /** * 往List中存入多个数据 * * @param key Redis键 * @param values 多个数据 * @return 存入的个数 */ public static long lPushAll(final String key, final Object... values) { Long count = redisTemplate.opsForList().rightPushAll(key, values); return count == null ? 0 : count; } /** * 从List中获取begin到end之间的元素 * * @param key Redis键 * @param start 开始位置 * @param end 结束位置(start=0,end=-1表示获取全部元素) * @return List对象 */ public static List<Object> lGet(final String key, final int start, final int end) { return redisTemplate.opsForList().range(key, start, end); } }
RedisTemplate工具类2
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; @Component public final class RedisUtil { @Autowired private RedisTemplate redisTemplate; // =============================common============================ public Set<String> keys(String pattern) { return redisTemplate.keys(pattern); } /** * 指定缓存失效时间 * * @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 <T> T get(String key) { if (key == null) return null; ValueOperations<String, T> operation = redisTemplate.opsForValue(); return operation.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 delta 要增加几(大于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 delta 要减少几(小于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<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().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<String, Object> map, long time) { try { redisTemplate.opsForHash().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 { redisTemplate.opsForHash().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 { redisTemplate.opsForHash().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) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash递减 * * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================set============================= /** * 根据key获取Set中的所有值 * * @param key 键 * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 = redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 = redisTemplate.opsForSet().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<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的长度 * * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().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 redisTemplate.opsForList().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 { redisTemplate.opsForList().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 { redisTemplate.opsForList().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<Object> value) { try { redisTemplate.opsForList().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<Object> value, long time) { try { redisTemplate.opsForList().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 { redisTemplate.opsForList().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 { return redisTemplate.opsForList().remove(key, count, value); } catch (Exception e) { e.printStackTrace(); return 0; } } }
基于jedis的redis工具类
以下为部分代码,完整的代码和redis应用实例,请移步到码云。
码云地址: https://gitee.com/JYFlyer/spring-boot-redis-case
/** * 基于jedis的redis操作工具类 * @author jyf * @time 2019/8/3 22:30 */ public final class RedisUtils { /* 除了该工具类提供的方法外,还可以在外面调用getJedis()方法,获取到jedis实例后,调用它原生的api来操作 */ /** * 获取jedis对象,并选择redis库。jedis默认是0号库,可传入1-16之间的数选择库存放数据 * 原则上使用一个redis库存放数据,通过特定的key的命令规则来区分不同的数据就行了。 * * @param index redis库号。使用可变参数的目的就是该参数可传可不传。 * @return 返回jedis对象 */ public static Jedis getJedis(int... index) { Jedis jedis = MyJedisPoolConfig.getJedisPool().getResource(); if (index != null && index.length > 0) { if (index[0] > 0 && index[0] <= 16){ jedis.select(index[0]); } } return jedis; } /*######################## key的操作 ################################*/ /** * 根据pattern返回当前库中的key * * @param pattern * @return */ public static Set<String> keys(String pattern) { Jedis jedis = null; Set<String> keys = null; try { jedis = getJedis(); keys = jedis.keys(pattern); }finally { if (jedis != null){ jedis.close(); } } return keys; } /** * 删除一个或多个key * * @param key 一个或多个key */ public static Long del(String... key) { Jedis jedis = null; Long delNum = 0L; try { jedis = getJedis(); delNum =jedis.del(key); }finally { if (jedis != null){ jedis.close(); } } return delNum; } /** * 批量删除 * @param keyList 要删除的key的集合 */ public static void mdel(List<String> keyList){ Jedis jedis = getJedis(); //获取pipeline Pipeline pipeline = jedis.pipelined(); for (String key : keyList) { pipeline.del(key); } //执行结果同步,这样才能保证结果的正确性。实际上不执行该方法也执行了上面的命令,但是结果确不一定完全正确。 //注意 pipeline.sync(); //关闭连接 jedis.close(); } /** * 判断某个key是否还存在 * * @param key key * @return */ public static Boolean exists(String key) { Jedis jedis = null; Boolean flag = false; try { jedis = getJedis(); flag = jedis.exists(key); }finally { if (jedis != null){ jedis.close(); } } return flag; } /** * 设置某个key的过期时间,单位秒 * * @param key key * @param seconds 过期时间秒 */ public static void expire(String key, int seconds) { Jedis jedis = null; try { jedis = getJedis(); jedis.expire(key, seconds); }finally { if (jedis != null){ jedis.close(); } } } /** * 查看某个key还有几秒过期,-1表示永不过期 ,-2表示已过期 * * @param key key * @return */ public static Long timeToLive(String key) { Jedis jedis = null; Long ttl; try { jedis = getJedis(); ttl = jedis.ttl(key); }finally { if (jedis != null){ jedis.close(); } } return ttl; } /** * 查看某个key对应的value的类型 * * @param key * @return */ public static String type(String key) { Jedis jedis = null; String type = null; try { jedis = getJedis(); type = jedis.type(key); }finally { if (jedis != null){ jedis.close(); } } return type; } /*######################## string(字符串)的操作 ####################*/ /** * 获取某个key的value,类型要对,只能value是string的才能获取 * * @param key * @return */ public static String get(String key) { Jedis jedis = null; String value = null; try { jedis = getJedis(); value = jedis.get(key); }finally { if (jedis != null){ jedis.close(); } } return value; } /** * 设置某个key的value * * @param key * @param value */ public static void set(String key, String value) { Jedis jedis = null; try { jedis = getJedis(); jedis.set(key, value); }finally { if (jedis != null){ jedis.close(); } } } /** * 字符串后追加内容 * * @param key key * @param appendContent 要追加的内容 */ public static void append(String key, String appendContent) { Jedis jedis = null; try { jedis = getJedis(); jedis.append(key, appendContent); }finally { if (jedis != null){ jedis.close(); } } } /** * 返回key的value的长度 * * @param key * @return */ public static Long strlen(String key) { Jedis jedis = null; Long strLen = 0L; try { jedis = getJedis(); strLen = jedis.strlen(key); }finally { if (jedis != null){ jedis.close(); } } return strLen; } /** * value 加1 必 * 须是字符型数字 * @param key * @return 增加后的值 */ public static Long incr(String key) { Jedis jedis = null; Long incrResult = 0L; try { jedis = getJedis(); incrResult = jedis.incr(key); }finally { if (jedis != null){ jedis.close(); } } return incrResult; } /** * value 减1 必须是字符型数字 * * @param key * @return */ public static Long decr(String key) { Jedis jedis = null; Long decrResult = 0L; try { jedis = getJedis(); decrResult = jedis.decr(key); }finally { if (jedis != null){ jedis.close(); } } return decrResult; } /** * value 加increment * * @param key key * @param increment 加几 * @return */ public static Long incrby(String key, int increment) { Jedis jedis = null; Long incrByResult = 0L; try { jedis = getJedis(); incrByResult = jedis.incrBy(key, increment); }finally { if (jedis != null){ jedis.close(); } } return incrByResult; } /** * value 减increment * * @param key * @param increment * @return */ public static Long decrby(String key, int increment) { Jedis jedis = null; Long decrByResult = 0L; try { jedis = getJedis(); decrByResult = jedis.decrBy(key, increment); }finally { if (jedis != null){ jedis.close(); } } return decrByResult; } /** * 给某个key设置过期时间和value,成功返回OK * * @param key key * @param seconds 过期时间秒 * @param value 设置的值 * @return */ public static String setex(String key, int seconds, String value) { Jedis jedis = null; String result = null; try { jedis = getJedis(); result = jedis.setex(key, seconds, value); }finally { if (jedis != null){ jedis.close(); } } return result; } /*######################## list(列表)的操作 #######################*/ //lpush rpush lpop rpop lrange lindex llen lset /** * 从左边向列表中添加值 * * @param key key * @param str 要添加的值 */ public static void lpush(String key, String str) { Jedis jedis = null; try { jedis = getJedis(); jedis.lpush(key, str); }finally { if (jedis != null){ jedis.close(); } } } /** * 从右边向列表中添加值 * * @param key key * @param str 要添加的值 */ public static void rpush(String key, String str) { Jedis jedis = null; try { jedis = getJedis(); jedis.rpush(key, str); }finally { if (jedis != null){ jedis.close(); } } } /** * 从左边取出一个列表中的值 * * @param key * @return */ public static String lpop(String key) { Jedis jedis = null; String lpop = null; try { jedis = getJedis(); lpop = jedis.lpop(key); }finally { if (jedis != null){ jedis.close(); } } return lpop; } /** * 从右边取出一个列表中的值 * * @param key * @return */ public static String rpop(String key) { Jedis jedis = null; String rpop = null; try { jedis = getJedis(); rpop = jedis.rpop(key); }finally { if (jedis != null){ jedis.close(); } } return rpop; } /** * 取出列表中指定范围内的值,0 到 -1 表示全部 * * @param key * @param startIndex * @param endIndex * @return */ public static List<String> lrange(String key, int startIndex, int endIndex) { Jedis jedis = null; List<String> result = null; try { jedis = getJedis(); result = jedis.lrange(key, startIndex, endIndex); }finally { if (jedis != null){ jedis.close(); } } return result; } /** * 返回某列表指定索引位置的值 * * @param key 列表key * @param index 索引位置 * @return */ public static String lindex(String key, int index) { Jedis jedis = null; String lindex = null; try { jedis = getJedis(); lindex = jedis.lindex(key, index); }finally { if (jedis != null){ jedis.close(); } } return lindex; } /** * 返回某列表的长度 * * @param key * @return */ public static Long llen(String key) { Jedis jedis = null; Long llen = 0L; try { jedis = getJedis(); llen = jedis.llen(key); }finally { if (jedis != null){ jedis.close(); } } return llen; } /** * 给某列表指定位置设置为指定的值 * * @param key * @param index * @param str */ public static void lset(String key, Long index, String str) { Jedis jedis = null; try { jedis = getJedis(); jedis.lset(key, index, str); }finally { if (jedis != null){ jedis.close(); } } } /** * 对列表进行剪裁,保留指定闭区间的元素(索引位置也会重排) * @param key 列表key * @param startIndex 开始索引位置 * @param endIndex 结束索引位置 */ public static void ltrim(String key,Integer startIndex,Integer endIndex){ Jedis jedis = null; try { jedis = getJedis(); jedis.ltrim(key, startIndex, endIndex); }finally { if (jedis != null){ jedis.close(); } } } /** * 从列表的左边阻塞弹出一个元素 * @param key 列表的key * @param timeout 阻塞超时时间,0表示若没有元素就永久阻塞 * @return */ public static List<String> blpop(String key,Integer timeout){ Jedis jedis = null; List<String> valueList = null; try { jedis = getJedis(); valueList = jedis.blpop(timeout, key); }finally { if (jedis != null){ jedis.close(); } } return valueList; } /** * 从列表的右边阻塞弹出一个元素 * @param key 列表的key * @param timeout 阻塞超时时间,0表示若没有元素就永久阻塞 * @return */ public static List<String> brpop(String key,Integer timeout){ Jedis jedis = null; List<String> valueList = null; try { jedis = getJedis(); valueList = jedis.brpop(timeout, key); }finally { if (jedis != null){ jedis.close(); } } return valueList; } /*######################## hash(哈希表)的操作 #######################*/ //hset hget hmset hmget hgetall hdel hkeys hvals hexists hincrby /** * 给某个hash表设置一个键值对 * * @param key * @param field * @param value */ public static void hset(String key, String field, String value) { Jedis jedis = null; try { jedis = getJedis(); jedis.hset(key, field, value); }finally { if (jedis != null){ jedis.close(); } } } /** * 取出某个hash表中某个field对应的value * * @param key key * @param field field * @return */ public static String hget(String key, String field) { Jedis jedis = null; String hget = null; try { jedis = getJedis(); hget = jedis.hget(key, field); }finally { if (jedis != null){ jedis.close(); } } return hget; } /** * 某个hash表设置一个或多个键值对 * * @param key * @param kvMap */ public static void hmset(String key, Map<String, String> kvMap) { Jedis jedis = null; try { jedis = getJedis(); jedis.hmset(key, kvMap); }finally { if (jedis != null){ jedis.close(); } } } /** * 取出某个hash表中任意多个key对应的value的集合 * * @param key * @param fields * @return */ public static List<String> hmget(String key, String... fields) { Jedis jedis = null; List<String> hmget = null; try { jedis = getJedis(); hmget = jedis.hmget(key, fields); }finally { if (jedis != null){ jedis.close(); } } return hmget; } /** * 取出某个hash表中所有的键值对 * * @param key * @return */ public static Map<String, String> hgetall(String key) { Jedis jedis = null; Map<String, String> kvMap = null; try { jedis = getJedis(); kvMap = jedis.hgetAll(key); }finally { if (jedis != null){ jedis.close(); } } return kvMap; } /** * 判断某个hash表中的某个key是否存在 * * @param key * @param field * @return */ public static Boolean hexists(String key, String field) { Jedis jedis = null; Boolean exists = null; try { jedis = getJedis(); exists = jedis.hexists(key, field); }finally { if (jedis != null){ jedis.close(); } } return exists; } /** * 返回某个hash表中所有的key * * @param key * @return */ public static Set<String> hkeys(String key) { Jedis jedis = null; Set<String> keys = null; try { jedis = getJedis(); keys = jedis.hkeys(key); }finally { if (jedis != null){ jedis.close(); } } return keys; } /** * 返回某个hash表中所有的value * * @param key * @return */ public static List<String> hvals(String key) { Jedis jedis = null; List<String> hvals = null; try { jedis = getJedis(); hvals = jedis.hvals(key); }finally { if (jedis != null){ jedis.close(); } } return hvals; } /** * 删除某个hash表中的一个或多个键值对 * * @param key * @param fields */ public static void hdel(String key, String... fields) { Jedis jedis = null; try { jedis = getJedis(); jedis.hdel(key, fields); }finally { if (jedis != null){ jedis.close(); } } } /** * 给某个hash表中的某个field的value增加多少 * * @param key hash表的key * @param field 表中的某个field * @param increment 增加多少 * @return */ public static Long hincrby(String key, String field, Long increment) { Jedis jedis = null; Long result = null; try { jedis = getJedis(); result = jedis.hincrBy(key, field, increment); }finally { if (jedis != null){ jedis.close(); } } return result; } /*######################## set(集合)的操作 ###########################*/ /** * 往set集合中添加一个或多个元素 * @param key key * @param members 要添加的元素 * @return 添加成功的元素个数 */ public static Long sadd(String key,String... members){ Jedis jedis = null; Long num = 0L; try { jedis = getJedis(); num = jedis.sadd(key, members); }finally { if (jedis != null){ jedis.close(); } } return num; } /** * 返回set集合中的所有元素,顺序与加入时的顺序一致 * @param key key * @return */ public static Set<String> smembers(String key){ Jedis jedis = null; Set<String> members = null; try { jedis = getJedis(); members = jedis.smembers(key); }finally { if (jedis != null){ jedis.close(); } } return members; } /** * 判断集合中是否存在某个元素 * @param key key * @param member 某个元素 * @return true存在,false不存在 */ public static Boolean sismember(String key,String member){ Jedis jedis = null; Boolean isMember = false; try { jedis = getJedis(); isMember = jedis.sismember(key, member); }finally { if (jedis != null){ jedis.close(); } } return isMember; } /** * 返回set集合的长度 * @param key key * @return */ public static Long scard(String key){ Jedis jedis = null; Long len = 0L; try { jedis = getJedis(); len = jedis.scard(key); }finally { if (jedis != null){ jedis.close(); } } return len; } /** * 删除set集合中指定的一个或多个元素 * @param key * @param members 要删除的元素 * @return 删除成功的元素个数 */ public static Long srem(String key,String... members){ Jedis jedis = null; Long num = 0L; try { jedis = getJedis(); num = jedis.srem(key,members); }finally { if (jedis != null){ jedis.close(); } } return num; } /** * 将key1中的元素key1Member移动到key2中 * @param key1 来源集合key * @param key2 目的地集合key * @param key1Member key1中的元素 * @return 1成功,0失败 */ public static Long smove(String key1,String key2,String key1Member){ Jedis jedis = null; Long num = 0L; try { jedis = getJedis(); num = jedis.smove(key1,key2,key1Member); }finally { if (jedis != null){ jedis.close(); } } return num; } /** * 随机查询返回集合中的指定个数的元素(若count为负数,返回的元素可能会重复) * @param key key * @param count 要查询返回的元素个数 * @return 元素list集合 */ public static List<String> srandmember(String key,int count){ Jedis jedis = null; List<String> members = null; try { jedis = getJedis(); members = jedis.srandmember(key,count); }finally { if (jedis != null){ jedis.close(); } } return members; } /** * 从set集合中随机弹出指定个数个元素 * @param key key * @param count 要弹出的个数 * @return 随机弹出的元素 */ public static Set<String> spop(String key,int count){ Jedis jedis = null; Set<String> members = null; try { jedis = getJedis(); members = jedis.spop(key,count); }finally { if (jedis != null){ jedis.close(); } } return members; } /** * 求交集,返回多个set集合相交的部分 * @param setKeys 多个set集合的key * @return 相交的元素集合 */ public static Set<String> sinter(String... setKeys){ Jedis jedis = null; Set<String> members = null; try { jedis = getJedis(); members = jedis.sinter(setKeys); }finally { if (jedis != null){ jedis.close(); } } return members; } /** * 求并集,求几个set集合的并集(因为set中不会有重复的元素,合并后的集合也不会有重复的元素) * @param setKeys 多个set的key * @return 合并后的集合 */ public static Set<String> sunion(String... setKeys){ Jedis jedis = null; Set<String> members = null; try { jedis = getJedis(); members = jedis.sunion(setKeys); }finally { if (jedis != null){ jedis.close(); } } return members; } /** * 求差集,求几个集合之间的差集 * @param setKeys 多个set的key * @return 差集 */ public static Set<String> sdiff(String... setKeys){ Jedis jedis = null; Set<String> members = null; try { jedis = getJedis(); members = jedis.sdiff(setKeys); }finally { if (jedis != null){ jedis.close(); } } return members; } /*######################## zset(有序集合)的操作 #######################*/ /** * 添加一个元素到zset * @param key key * @param score 元素的分数 * @param member 元素 * @return 成功添加的元素个数 */ public static Long zadd(String key,double score, String member){ Jedis jedis = null; Long num = null; try { jedis = getJedis(); num = jedis.zadd(key,score,member); }finally { if (jedis != null){ jedis.close(); } } return num; } }
-
java操作redis工具类
2018-11-10 21:17:13org.springframework.data.redis.core.StringRedisTemplate,spring boot集成redis后操作类,封装后完全是针对redis命令调用 -
springboot(四):redis的配置和redis工具类封装
2020-05-12 16:02:06redis的安装和启动 redis支持mac,window,linux 官方下载地址:https://redis.io/download git下载地址:https://github.com/microsoftarchive/redis/releases 对于mac系统 解压文件 在命令行用cd 命令进入解压后...redis的安装和启动
redis支持mac,window,linux
官方下载地址:https://redis.io/download
git下载地址:https://github.com/microsoftarchive/redis/releases对于mac系统
- 解压文件
- 在命令行用
cd
命令进入解压后的文件目录 - 输入
make
,完成安装。 - 通过命令行 执行
src/redis-server
即可启动Redis服务
对于window系统
- msi是可执行文件,按安装步骤安装即可。zip直接解压就可以了。
- 同样进入目录 执行redis-server即可启动redis。
这边有关redis的一些设置不讲太多,只是做最简单的安装和启动。有兴趣的可以自己研究研究里面的设置。
pom.xml配置
<!-- redis start --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.8.0</version> </dependency> <!-- redis end -->
application.properties配置
# 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.lettuce.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.lettuce.pool.max-wait=10000ms # 连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.lettuce.timeout=0
Redis配置类
RedisConfig.java
package com.admin.zhou.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @author: zhou * @Date: 2019/10/5 * Describe: redis配置文件 * @return */ @Configuration @EnableCaching public class RedisConfig { /** * 缓存管理器 */ @Bean public CacheManager cacheManager(LettuceConnectionFactory factory) { //以锁写入的方式创建RedisCacheWriter对象 RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory); //创建默认缓存配置对象 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); RedisCacheManager cacheManager = new RedisCacheManager(writer, config); return cacheManager; } /** * RedisTemplate */ @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(factory); 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); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
redis封装工具类
RedisUtil.java
package com.admin.zhou.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Redis工具类 */ @Component public class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; /****************** common start ****************/ /** * 指定缓存失效时间 * @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)); } } } /****************** common end ****************/ /****************** String start ****************/ /** * 普通缓存获取 * @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 delta 要增加几(大于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 delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } /****************** String end ****************/ /****************** Map start ****************/ /** * 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<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().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<String, Object> map, long time) { try { redisTemplate.opsForHash().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 { redisTemplate.opsForHash().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 { redisTemplate.opsForHash().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) { redisTemplate.opsForHash().delete(key, item); } /** * 判断hash表中是否有该项的值 * @param key 键 不能为null * @param item 项 不能为null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash递增 如果不存在,就会创建一个 并把新增后的值返回 * @param key 键 * @param item 项 * @param by 要增加几(大于0) * @return */ public double hincr(String key, String item, long by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash递减 * @param key 键 * @param item 项 * @param by 要减少记(小于0) * @return */ public double hdecr(String key, String item, long by) { return redisTemplate.opsForHash().increment(key, item, -by); } /****************** Map end ****************/ /****************** Set start ****************/ /** * 根据key获取Set中的所有值 * @param key 键 * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 = redisTemplate.opsForSet().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 redisTemplate.opsForSet().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 = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /****************** Set end ****************/ /****************** List start ****************/ /** * 获取list缓存的内容 * @param key 键 * @param start 开始 * @param end 结束 0 到 -1代表所有值 * @return */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取list缓存的长度 * @param key 键 * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().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 redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().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 { redisTemplate.opsForList().rightPush(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将list放入缓存 * @param key 键 * @param value 值 * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().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<Object> value, long time) { try { redisTemplate.opsForList().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 { redisTemplate.opsForList().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 = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } /****************** List end ****************/ }
这样redis的配置就完成了。
测试
在测试的controller里面加入
@RestController public class TestController { @Autowired public RedisUtil redisUtil; @RequestMapping("/getReidsTest") public String getReidsTest(){ String testStr = (String) redisUtil.get("test"); if (StringUtils.isEmpty(testStr)){ redisUtil.set("test","content"); return "还未加入redis,第一次加入"; } return "redis缓存内容:"+testStr; } }
启动redis,启动项目。第一次redis没有缓存test的内容,则页面显示
还未加入redis,第一次加入
第二次以后,redis缓存了test的内容,显示redis缓存内容:content
说明redis已经成功启动且可以缓存相关数据。源码git地址:https://gitee.com/stonezry/Springboot-Admin-Demo
欢迎关注本人公众号和小程序,谢谢
-
Redis(七) - 封装Redis工具类
2022-07-20 16:01:07Redis(七) - 封装Redis工具类 -
Redis操作Hash工具类封装,Redis工具类封装
2020-10-22 14:55:26/**************************** redis Hash start***************************/ /***Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象。***/ /** * 设置Hash的属性 * @param key ... -
Redis学习之路(八)封装Redis工具类
2022-04-06 11:03:40文章目录一、工具类的需求1、方法一2、方法二 一、工具类的需求 1、方法一 public <R,ID> R queryWithPassThrough(String keyPrefix, ID id , Class<R> type, Function<ID,R> dbFallback,Long ... -
jedis操作redis工具类,使用该工具类无需配置spring
2016-02-18 10:53:37该类是jedis操作redis的工具类,使用该工具类之后,无需配置spring,只需要显示调用工具类中的方法就好了。此类为工作中在用,所以确定可用。 共有两个类,一个工具类和一个测试调用demo -
封装redis工具类——缓存工具类
2022-06-27 19:30:53基于StringRedisTemplate封装一个缓存工具类,满足下列要求:方法1:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL时间 方法2:将任意Java对象序列化为json并存储在string类型的key中,... -
springboot中对redis的操作封装工具类
2022-03-01 19:24:44我们可以自己写一个工具类把redisTemplate进行封装,方便我们调用。这是一种很好的开发方式,简化开发。 狂神教程中的封装 package com.kuang.utils; import org.springframework.beans.factory.annotation.... -
Java封装独立的Redis工具类【附简单使用】
2021-01-29 13:12:59import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.core.ZSetOperations; import java.util.List; import java.util.Map; import java.util.Set; import java.... -
JAVA中对Redis封装工具类-RedisUtil
2022-04-07 12:03:25Java中对redis的封装 1.maven依赖 <!--版本号和spring parent版本号一致--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data... -
Spring Boot系列 —(五)SpringBoot 项目整合 Redis 封装工具类
2022-02-12 16:55:07SpringBoot 项目项目整合 Redis 封装工具类 -
Redis工具类封装讲解和实战
2020-06-06 11:18:45Redis工具类封装讲解和实战 简介:高效开发方式 Redis工具类封装讲解和实战 1、常用客户端 https://redisdesktop.com/download 2、封装redis工具类并操作 package net.leon.base_project.utils; import java.... -
redis(二)使用redis工具类
2022-02-24 11:31:02redis官网提供了很多开源的C#客户端。其中ServiceStack.Redis应该算是比较流行的。它提供了一整套从Redis数据结构的强数据类型转换的机制并将对象json序列化。 ServiceStack.Redis地址:... -
Redis工具类封装RedisUtils
2019-02-26 14:34:37本文参考:... SpringBoot项目集成Redis相当简单,只需要pom中加入对应依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>sp... -
使用python封装Redis工具类
2021-11-14 19:16:22启动redis服务端 ...封装工具类 import redis class RedisHelper: def __init__(self, host, password, port): # 连接redis self.__redis = redis.StrictRedis(host=host, password=password, po -
常用的Redis封装工具类
2020-06-03 17:15:50import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.Set; import java.util.co. -
Java代码封装redis工具类
2018-08-02 13:49:00maven依赖关系: <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version... -
小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_40、Redis工具类封装讲解和...
2019-10-02 09:47:174、Redis工具类封装讲解和实战 简介:高效开发方式 Redis工具类封装讲解和实战 1、常用客户端 https://redisdesktop.com/download 2、封装redis工具类并操作 开始 主要讲开发中的技巧 Redis 桌面管理工具... -
Redis工具类
2019-09-27 15:50:53Redis工具类,已封装,下载解压直接可以引用,非常方便 -
Redis实战(十二)-工具类封装(全类型操作/分布式锁/消息队列/自增序列)
2021-09-16 22:00:32 平时工作中,我们只需要把Redis相关操作抽离到common包... 下面就是工作中抽离出的Redis操作的工具类代码。 1、maven父级依赖 <groupId>org.springframework.boot <artifactId>spring-boot-starter-parent -
PHP实现操作redis的封装类完整实例
2021-09-13 10:18:42本文实例讲述了PHP实现操作Redis的封装类。分享给大家供大家参考,具体如下: <?php /** * Redis 操作,支持 Master/Slave 的负载集群 * * @author jackluo */ class RedisCluster{ // 是否使用 M/S 的... -
springboot使用已封装好的redis工具类进行操作
2018-09-07 17:22:40请结合springboot学习教程项目github地址 ... 工具类 RedisOperator package com.imooc.utils; import java.util.Map; import java.util.Set; import java.util.concurrent.Tim... -
golang redis封装工具
2019-07-08 15:59:501、redistools代码 package redistools import ( "github.com/garyburd/redigo/redis" "time" ) type RedisDataStore struct { RedisHost string RedisDB string RedisPwd string Timeout int64 RedisP.....