Redis缓存:高性能数据存储
Redis缓存:高性能数据存储
概述
Redis是一个开源的内存数据库,它支持多种数据结构,具有高性能、高可用的特点,广泛应用于缓存、会话管理、消息队列等场景。
1. Redis数据结构
@Component
public class RedisDataStructure {
private final StringRedisTemplate redisTemplate;
public void stringDemo() {
redisTemplate.opsForValue().set("name", "John");
String name = redisTemplate.opsForValue().get("name");
}
public void hashDemo() {
Map<String, String> map = new HashMap<>();
map.put("name", "John");
map.put("age", "25");
redisTemplate.opsForHash().putAll("user:1", map);
}
public void listDemo() {
redisTemplate.opsForList().leftPush("queue", "task1");
String task = redisTemplate.opsForList().leftPop("queue");
}
public void setDemo() {
redisTemplate.opsForSet().add("tags", "java", "spring", "redis");
Set<String> tags = redisTemplate.opsForSet().members("tags");
}
public void zSetDemo() {
redisTemplate.opsForZSet().add("leaderboard", "player1", 100);
Set<String> topPlayers = redisTemplate.opsForZSet()
.reverseRange("leaderboard", 0, 9);
}
}
2. Spring Boot + Redis
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.CacheEvict;
@Service
public class UserService {
@Cacheable(value = "users", key = "#id")
public User findById(Long id) {
return userRepository.findById(id).orElse(null);
}
@CachePut(value = "users", key = "#user.id")
public User update(User user) {
return userRepository.save(user);
}
@CacheEvict(value = "users", key = "#id")
public void delete(Long id) {
userRepository.deleteById(id);
}
}
3. 缓存策略
@Service
public class CacheStrategy {
private final StringRedisTemplate redisTemplate;
// 缓存穿透:查询不存在的数据 -> 缓存空值
public User getUserWithNullCache(Long id) {
String cacheKey = "user:" + id;
String cached = redisTemplate.opsForValue().get(cacheKey);
if ("NULL".equals(cached)) return null;
if (cached != null) return JSON.parseObject(cached, User.class);
User user = userRepository.findById(id).orElse(null);
if (user == null) {
redisTemplate.opsForValue().set(cacheKey, "NULL", 5, TimeUnit.MINUTES);
} else {
redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(user), 30, TimeUnit.MINUTES);
}
return user;
}
}
4. 分布式锁
@Service
public class DistributedLock {
private final StringRedisTemplate redisTemplate;
public boolean tryLock(String lockKey, long timeout) {
return redisTemplate.opsForValue()
.setIfAbsent(lockKey, "1", timeout, TimeUnit.SECONDS);
}
public void unlock(String lockKey) {
redisTemplate.delete(lockKey);
}
}
最佳实践
- 选择合适的数据结构:根据场景选择String/Hash/List/Set/ZSet
- 设置过期时间:避免内存溢出
- 缓存策略:根据场景选择合适的缓存策略
- 分布式锁:使用Redis实现分布式锁
- 监控Redis:使用Redis监控工具
总结
Redis是一款高性能的内存数据库,掌握Redis的数据结构和使用方式,可以实现高性能的缓存方案。