2.2、使用示例
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public CustomersEntity findById(Integer id) {
// 需要缓存
// 所有涉及的缓存都需要删除,或者更新
try {
String toString = stringRedisTemplate.opsForHash().get(REDIS_CUSTOMERS_ONE, id + “”).toString();
if (toString != null) {
return JSONUtil.toBean(toString, CustomersEntity.class);
}
} catch (Exception e) {
e.printStackTrace();
}
// 缓存为空的时候,先查,然后缓存redis
Optional byId = customerRepo.findById(id);
if (byId.isPresent()) {
CustomersEntity customersEntity = byId.get();
try {
stringRedisTemplate.opsForHash().put(REDIS_CUSTOMERS_ONE, id + “”, JSONUtil.toJsonStr(customersEntity));
} catch (Exception e) {
e.printStackTrace();
}
return customersEntity;
}
return null;
}
2.3、扩展
2.3.1、spring-boot-starter-data-redis的依赖包
3.3.2、stringRedisTemplate API(部分展示)
-
opsForHash --> hash操作
-
opsForList --> list操作
-
opsForSet --> set操作
-
opsForValue --> string操作
-
opsForZSet --> Zset操作
3.3.3 StringRedisTemplate默认序列化机制
public class StringRedisTemplate extends RedisTemplate<String, String> {
/**
* Constructs a new StringRedisTemplate
instance. {@link #setConnectionFactory(RedisConnectionFactory)}
* and {@link #afterPropertiesSet()} still need to be called.
*/
public StringRedisTemplate() {
RedisSerializer stringSerializer = new StringRedisSerializer();
setKeySerializer(stringSerializer);
setValueSerializer(stringSerializer);
setHashKeySerializer(stringSerializer);
setHashValueSerializer(stringSerializer);
}
}
三、RedissonClient 操作示例
3.1 基本配置
3.1.1、Maven pom 引入
org.springframework.boot
spring-boot-starter-data-redis
org.redisson
redisson
3.8.2
true
org.redisson
redisson-spring-boot-starter
LATEST