RedisTemplate操作String及Hash数据方式
作者:ybb_ymm
本文主要介绍了使用RedisTemplate封装操作方法,包括单个和多个key的删除、设置key失效时间、获取key过期时间、判断key是否存在、String类型操作(如添加、删除缓存、顺序递增递减)以及Hash类型数据操作(如添加缓存数据、设置过期时间等)
RedisTemplate用法
封装自己的操作方法
1、单个key的删除(我们可以是封装自己的一个delete方法,然后将参数设置为key,在通过redisTemplate调用delete方法删除)
redisTemplate.delete(key)
2、多个key的删除(多个key删除则和上面的单key一样,只不过是在参数上设置为多个key的方式即可)
redisTemplate.delete(keys)
这里的keys是指的多参数:public void deleteByKey(String ...keys)
3、指定key失效时间(设置失效时间,我们自己定义的方法设置三个参数,分比为key,时间,单位《秒或分》)
redisTemplate.expir(key,time,TimeUnit.MINUTES)
4、根据key值获取过期的时间(我们自己设置key参数,然后通key获取过期时间)
redisTemplate.getExpire(key)
5、判断key是否已经存在(经常会用到的key是否存在,则和上面的方法类似,只是设置个key参数值)
redisTemplate.hasKey(key)
String 类型的操作
1、添加缓存
// 通过redisTemplate设置值
redisTemplate.boundValueOps("StringKey").set("StringValue");
redisTemplate.boundValueOps("StringKey").set("StringValue",1, TimeUnit.MINUTES);
//通过BoundValueOperations设置值
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
stringKey.set("StringVaule");
stringKey.set("StringValue",1, TimeUnit.SECOND);
//通过ValueOperations设置值
ValueOperations ops = redisTemplate.opsForValue();
ops.set("StringKey", "StringVaule");
ops.set("StringValue","StringVaule",1, TimeUnit.SECOND);2、删除缓存key
Boolean i = redisTemplate.delete(key)
3、顺序递增
redisTemplate.boundValueOps("key").increment(4L)4、顺序递减
redisTemplate.boundValueOps("key").increment(-4L)Hash 类型数据相关操作
1、添加我们的缓存数据
redisTemplate.boundHashOps("HashKey").put("SmallKey", "HashVaue");
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
hashKey.put("SmallKey", "HashVaue");
HashOperations hashOps = redisTemplate.opsForHash();
hashOps.put("HashKey", "SmallKey", "HashVaue");2、设置过期的时间
redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.SECOND);
redisTemplate.expire("HashKey",1,TimeUnit.SECOND);3、添加一个Map类型的数据
HashMap<String, String> hashMap = new HashMap<>();
redisTemplate.boundHashOps("HashKey").putAll(hashMap );4、提取所有的的小key值
Set keys1 = redisTemplate.boundHashOps("HashKey").keys();
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
Set keys2 = hashKey.keys();
HashOperations hashOps = redisTemplate.opsForHash();
Set keys3 = hashOps.keys("HashKey");总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
