- StringRedistemplate继承Redistemplate。
- 两者的数据是不共通的;也就是说StringRedistemplate只能管理StringRedistemplate里面的数据,Redistemplate只能管理Redistemplate中的数据。
两者之间的区别主要在于使用的序列化类:
- Redistemplate使用的是JdkSerializationRedisSerializer,存入数据会将数据先序列化成字节数组然后在存入Redis数据库。
- StringRedistemplate使用的是StringRedisSerializer。
Redistemplate
Redistemplate 中存取数据都是字节数组。当redis中存入的数据是可读形式而非字节数组时,使用redistemplate取值的时候会无法获取导出数据,获得的值为null。Redistemplate中定义了以下5种数据结构操作:redistemplate.opsForValue(); //操作字符串 redistemplate.opsForHash(); //操作hash redistemplate.opsForList(); //操作list redistemplate.opsForSet(); //操作set redistemplate.opsForZSet(); //操作有序set
StringRedistemplate
stringRedistemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//向redis里存入数据和设置缓存时间 stringRedistemplate.boundValueOps("test").increment(-1);//val做-1操作 stringRedistemplate.opsForValue().get("test")//根据key获取缓存中的val stringRedistemplate.boundValueOps("test").increment(1);//val +1 stringRedistemplate.getExpire("test")//根据key获取过期时间 stringRedistemplate.getExpire("test",TimeUnit.SECONDS)//根据key获取过期时间并换算成指定单位 stringRedistemplate.delete("test");//根据key删除缓存 stringRedistemplate.hasKey("546545");//检查key是否存在,返回boolean值 stringRedistemplate.opsForSet().add("red_123", "1","2","3");//向指定key中存放set集合 stringRedistemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);//设置过期时间 stringRedistemplate.opsForSet().isMember("red_123", "1")//根据key查看集合中是否存在指定数据 stringRedistemplate.opsForSet().members("red_123");//根据key获取set集合StringRedistemplate的使用
@RestController @RequestMapping("/user") public class UserResource { private static final Logger log = LoggerFactory.getLogger(UserResource.class); @Autowired private UserService userService; @Autowired public StringRedistemplate stringRedistemplate; @RequestMapping("/num") public String countNum() { String userNum = stringRedistemplate.opsForValue().get("userNum"); if(StringUtils.isNull(userNum)){ stringRedistemplate.opsForValue().set("userNum", userService.countNum().toString()); } return userNum; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。