Spring整合的Redis工具类
不多说,直接上代码,可自行扩展!
1 import org.springframework.data.redis.core.HashOperations; 2 import org.springframework.data.redis.core.RedisTemplate; 3 import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; 4 import org.springframework.stereotype.Component; 5 6 import javax.annotation.Resource; 7 import java.util.List; 8 import java.util.Map; 9 import java.util.concurrent.TimeUnit; 10 11 /** 12 * 现在一般使用这个RedisTemplate,会以二进制形式存储数据到redis中 13 * @ author:xuqing 14 * @ date:2020/8/9 13:08 15 */ 16 @Component 17 public final class RedisTemplateUtils { 18 19 /** 20 * 注意此处一定要使用@Resource注解,使用@Autowired获取不到这个RedisTemplate的 21 */ 22 @Resource 23 private RedisTemplate<String, Object> redisTemplate; 24 25 /** 26 * 存放list集合数据进redis 27 * @param key list数据对应的key 28 * @param list 需要存放的list数据 29 */ 30 public void setList(String key,List<Object> list){ 31 redisTemplate.opsForList().leftPushAll(key,list); 32 } 33 34 public <T> List<T> getList(String key){ 35 @SuppressWarnings("unchecked") 36 List<T> list = (List<T>) redisTemplate.opsForList().range(key, 0, 10); 37 System.out.println("通过range(K key, long start, long end)方法获取指定范围的集合值:"+list); 38 return list; 39 } 40 41 /** 42 * 设置String类型key的对象 43 * @param key 44 * @param object 45 */ 46 public void setObject(String key, Object object) { 47 redisTemplate.opsForValue().set(key, object); 48 } 49 50 /** 51 * 设置String类型key的对象,带有过期时间 52 * @param key 53 * @param object 54 * @param timeOut 55 */ 56 public void setObject(String key, Object object, Long timeOut) { 57 redisTemplate.opsForValue().set(key, object); 58 if (timeOut != null) { 59 redisTemplate.expire(key, timeOut, TimeUnit.SECONDS); 60 } 61 } 62 63 /** 64 * 获取指定key的对象数据 65 * @param key 66 * @return 67 */ 68 public Object getObject(String key) { 69 return redisTemplate.opsForValue().get(key); 70 } 71 72 /** 73 * 存储数据或修改数据 74 * 75 * @param modelMap 76 * @param mapName 77 */ 78 public void setKey(String mapName, Map<String, Object> modelMap) { 79 HashOperations<String, String, Object> hps = redisTemplate.opsForHash(); 80 hps.putAll(mapName, modelMap); 81 } 82 83 /** 84 * 获取数据Map 85 * 86 * @param mapName 87 * @return 88 */ 89 public Map<String, Object> getMapValue(String mapName) { 90 HashOperations<String, String, Object> hps = this.redisTemplate.opsForHash(); 91 return hps.entries(mapName); 92 93 } 94 95 /** 96 * 获取数据value 97 * 98 * @param mapName 99 * @param hashKey 100 * @return 101 */ 102 public Object getValue(String mapName, String hashKey) { 103 HashOperations<String, String, Object> hps = this.redisTemplate.opsForHash(); 104 return hps.get(mapName, hashKey); 105 106 } 107 108 /** 109 * 批量删除缓存数据 110 * 111 * @param keys 112 */ 113 public void deleteData(List<String> keys) { 114 // 执行批量删除操作时先序列化template 115 redisTemplate.setKeySerializer(new JdkSerializationRedisSerializer()); 116 redisTemplate.delete(keys); 117 } 118 119 }