springboot整合redis时提供了两个模板工具类,StringRedisTemplate和RedisTemplate.
当存储的value类型为对象类型使用redisTemplate
存储的valve类型为字符串。StringRedisTemplate
StringRedisTemplate
(1) 引入相关的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置文件
StringRedisTemplate该类把对每种数据类型的操作,单独封了相应的内部类。
对string操作
都封装在.opsForValue()中
public void mytest(){
//删除指定的key
Boolean k1 = redisTemplate.delete("k1");
//查看所有的key
Set<String> keys = redisTemplate.keys();
//是否存在指定的key
Boolean aBoolean = redisTemplate.hasKey();
//对字符串数据类型的操作ValueOperations
ValueOperations<String, String> forValue = redisTemplate.opsForValue();
//存储字符串类型--可以设置过期时间
forValue.set("k1","张三",30, TimeUnit.SECONDS);
//等价于setnx判断存入 存入成功返回true,失败返回false
Boolean absent = forValue.setIfAbsent("k2", "李四", 30, TimeUnit.SECONDS);
System.out.println(absent);
/*在指定k后追加内容*/
Integer append = forValue.append("k2", "真帅");
/*获取指定值*/
String key = forValue.get("k2");
}
对hash类操作
封装在.opsForHash()
public void mya(){
//获取hash类对象
HashOperations<String, Object, Object> forHash = redisTemplate.opsForHash();
/*存值*/
forHash.put("k1","name","张三");
forHash.put("k1","age","19");
/*一次存多个*/
Map<String,String> map=new HashMap<>();
map.put("name","李四");
map.put(&