微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring Data Redis应用场景分析

在Spring Boot中,认集成的redis是Spring Data Redis。Spring Data Redis针对redis提供了非常方便的操作模版Redistemplate,同时又提供了StringRedistemplate。本文来谈谈二者的关系:
  • StringRedistemplate继承Redistemplate。
  • 两者的数据是不共通的;也就是说StringRedistemplate只能管理StringRedistemplate里面的数据,Redistemplate只能管理Redistemplate中的数据。

两者之间的区别主要在于使用的序列化类:

  • Redistemplate使用的是JdkSerializationRedisSerializer,存入数据会将数据先序列化成字节数组然后在存入Redis数据库。 
  • StringRedistemplate使用的是StringRedisSerializer。
当Redis数据库里面本来存的是字符串数据或者要存取的数据就是字符串类型数据的时候,那么使用StringRedistemplate即可。如果数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取出一个对象,那么使用Redistemplate是更好的选择。

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 举报,一经查实,本站将立刻删除。

相关推荐