1)使用StringTemplateRedis操作String类型
1)判断redis中是否拥有key所对应的值,如果有返回true,没有那么直接返回false
redisTemplate.hasKey(key);
2)如果redis中有key那么直接取出key所对应的值
redisTemplate.opsForValue().get(key)
3)删除单个key值
redisTemplate.delete(key)
4)批量删除key值
redisTemplate.delete(keys),这里面的keys是Collections<K> keys类型
5)将当前传入的key值序列化为byte[]类型 redisTemplate.dump(key)
6)设置过期时间
redisTemplate.expire(key, timeout, unit)
redisTemplate.expireAt(key, date);
@Controller public class DemoRedis { @Autowired private StringRedisTemplate template; @RequestMapping("/Java100") @ResponseBody public String start(){ template.opsForValue().set("name","zhangsan"); template.expire("name",20, TimeUnit.SECONDS); return template.opsForValue().get("name"); } }
7)查找匹配的key值,返回一个Set集合类型
redisTemplate.keys(pattern)//patten可以传递一个*
/** * 根据前缀获取所有的key * 例如:pro_* */ public Set<String> getListKey(String prefix) { Set<String> keys = redisTemplate.keys(prefix.concat("*")); return keys; }
@Controller public class DemoRedis { @Autowired private StringRedisTemplate template; @RequestMapping("/Java100") @ResponseBody public String start(String pattern1,String pattern2){ template.opsForValue().set("userID","1"); template.opsForValue().set("username","zhangsna"); template.opsForValue().set("userdata","12503487"); StringBuilder builder=new StringBuilder(); Set<String> set1=template.keys(pattern1); for(String key:set1){ builder.append(key); } builder.append("\n"); //前缀进行获取 Set<String> set2=template.keys(pattern2.concat("*")); for(String key:set2){ builder.append(key); } builder.append("\n"); //批量获取value List<String> value1= template.opsForValue().multiGet(set1); value1.stream().forEach((String key)->{ builder.append(value1); }); return builder.toString(); } }
8) 批量获取value
/** * 获取所有的key */ public List<String> getListKey(String prefix) { Set<String> keys = redisTemplate.keys("*"); List<String> values = redisTemplate.opsForValue().multiGet(keys); return values; }
(411条消息) spring-data-redis概述及用法_spring data redis_jsxllht的博客-CSDN博客