一、Redis概述
Redis(Remote Dictionary Server)是一款高性能的键值存储数据库,支持多种数据结构(String, Hash, List, Set等),具备数据持久化、事务、发布订阅等特性,广泛应用于缓存、会话管理、实时排行榜等场景。
核心优势:
- 内存存储:毫秒级读写性能
- 数据结构丰富:支持字符串/哈希/列表等复杂结构
- 持久化机制:RDB快照与AOF日志保障数据安全
- 高可用方案:支持主从复制与集群模式
二、Redis核心命令速查
1. 通用命令
KEYS * # 查询所有键(生产慎用)
DEL user:1001 # 删除键
EXPIRE key 30 # 设置30秒过期
TTL key # 查看剩余生存时间
TYPE key # 获取键类型
2. 字符串(String)
SET name "John" # 设置值
GET name # 获取值
INCR counter # 数值自增1
APPEND msg " hello" # 字符串追加
3. 哈希(Hash)
HSET user:1001 name John age 28 # 设置字段
HGET user:1001 age # 获取字段
HGETALL user:1001 # 获取全部字段
HDEL user:1001 age # 删除字段
4. 列表(List)
LPUSH tasks "task1" # 左端插入
RPOP tasks # 右端弹出
LRANGE tasks 0 -1 # 获取全部元素
LLEN tasks # 获取列表长度
5. 集合(Set)
SADD tags "redis" "db" # 添加元素
SMEMBERS tags # 获取所有元素
SINTER set1 set2 # 求交集
SISMEMBER tags "redis" # 判断是否存在
6. 有序集合(Sorted Set)
ZADD ranking 100 "user1" 90 "user2" # 添加带分数成员
ZRANGE ranking 0 -1 WITHSCORES # 按分数升序排列
ZREVRANGE ranking 0 10 # 获取前10名
三、Spring Boot集成实战
1. 环境配置
pom.xml依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.yml配置:
spring:
redis:
host: 127.0.0.1
port: 6379
password: yourpassword
database: 0
2. 模板类操作示例
字符串操作:
@Autowired
private StringRedisTemplate stringRedisTemplate;
// 写入缓存
stringRedisTemplate.opsForValue().set("welcome_msg", "Hello Redis!");
// 读取并自增
Long views = stringRedisTemplate.opsForValue().increment("page:home:views");
哈希操作:
HashOperations<String, String, String> hashOps = stringRedisTemplate.opsForHash();
hashOps.put("user:1001", "name", "Alice");
String name = hashOps.get("user:1001", "name");
发布订阅功能:
// 发布消息
stringRedisTemplate.convertAndSend("news", "Breaking News!");
// 订阅处理(需实现MessageListener接口)
@Component
public class NewsSubscriber implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("Received: " + new String(message.getBody()));
}
}
3. 对象序列化配置
自定义RedisTemplate:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
template.setDefaultSerializer(serializer);
return template;
}
// 使用示例
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void saveUser(User user) {
redisTemplate.opsForValue().set("user:"+user.getId(), user);
}
4. 缓存注解应用
启用缓存:
@SpringBootApplication
@EnableCaching
public class App { ... }
方法级缓存:
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
// 数据库查询操作
}
@CacheEvict(value = "products", key = "#id")
public void updateProduct(Product product) { ... }
四、典型应用场景
- 会话缓存:存储用户登录状态
// 存储Session
stringRedisTemplate.opsForValue().set(sessionId, userInfo, 30, TimeUnit.MINUTES);
- 排行榜实时更新:
// 更新分数
redisTemplate.opsForZSet().add("leaderboard", playerId, score);
// 获取TOP10
Set<Object> topPlayers = redisTemplate.opsForZSet().reverseRange("leaderboard", 0, 9);
- 分布式锁实现:
public boolean tryLock(String key, String value, long expireTime) {
return redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
}
- 限流控制:
// 使用INCR实现简单限流
Long count = stringRedisTemplate.opsForValue().increment("api:login:"+userId, 1);
if(count > 100) {
throw new RateLimitException();
}
五、性能优化建议
- 合理设置过期时间避免内存溢出
- Pipeline批量操作减少网络开销
- 使用Scan替代Keys命令
- 配置合适的持久化策略
- 监控内存使用与慢查询
六、总结
通过Spring Data Redis,开发者可以便捷地集成Redis到应用中。掌握核心数据结构的操作命令,配合Spring的注解驱动开发,能快速实现缓存、分布式锁等高并发场景需求。建议结合官方文档深入理解各命令的时间复杂度,根据业务特点选择最佳实践方案。
扩展学习:
- Redis官方命令手册:https://redis.io/commands
- Spring Data Redis文档:https://spring.io/projects/spring-data-redis
- Redis集群搭建与性能调优
通过合理运用Redis,可显著提升系统性能与扩展能力,成为高并发架构中的重要基石。