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

StringRedisTemplate操作redis数据

1、StringRedisTemplate操作redis数据

 

StringRedistemplate与Redistemplate区别点

  • 两者的关系是StringRedistemplate继承Redistemplate。

  • 两者的数据是不共通的;也就是说StringRedistemplate只能管理StringRedistemplate里面的数据,Redistemplate只能管理Redistemplate中的数据。

  • 其实他们两者之间的区别主要在于他们使用的序列化类:

    Redistemplate使用的是JdkSerializationRedisSerializer    存入数据会将数据先序列化成字节数组然后在存入Redis数据库。 

      StringRedistemplate使用的是StringRedisSerializer

  • 使用时注意事项:
   当你的redis数据库里面本来存的是字符串数据或者你要存取的数据就是字符串类型数据的时候,那么你就使用StringRedistemplate即可。    但是如果你的数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取出一个对象,那么使用Redistemplate是更好的选择。
  • Redistemplate使用时常见问题:

    redistemplate 中存取数据都是字节数组。当redis中存入的数据是可读形式而非字节数组时,使用redistemplate取值的时候会无法获取导出数据,获得的值为null。可以使用 StringRedistemplate 试试。

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的使用 

 springboot中使用注解@Autowired 即可

1 2 @Autowired public StringRedistemplate 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;
    }
}

复制代码

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐