Spring Data Redis

Spring Data Redis

一、Spring Data Redis 是什么?

可以把 Spring Data 理解成一个"数据库访问全家桶",它把各种数据库的访问都封装成统一的接口,让开发者不用去写一堆重复的"连接、关闭、异常处理"代码。Redis 作为内存数据库,自然也被收编进来,这就是 Spring Data Redis。

它的核心目标:用更少的代码,做更多的 Redis 操作,而且还能保持优雅。

二、为什么用 RedisTemplate 而不是 Jedis?

Jedis 是 Redis 官方推荐的 Java 客户端,功能齐全,但 Spring Boot 2.x 之后,默认底层换成了 Lettuce。

  • Lettuce vs Jedis:Lettuce 基于 Netty,支持异步和响应式编程,在高并发场景下表现更优秀。Jedis 是阻塞式的,多线程环境下需要自己管理连接池。
  • RedisTemplate 的优势:Spring 提供的 RedisTemplate 对底层客户端(无论是 Lettuce 还是 Jedis)做了高度封装,提供了统一的操作接口,并且支持灵活的序列化策略。
三、快速上手

引入依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置文件(application.yml)

yaml 复制代码
spring:
  redis:
    host: localhost
    port: 6379
    password: yourpassword  # 如果没有密码可以删掉这行
    database: 0
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

配置 RedisTemplate(解决序列化乱码问题)

java 复制代码
@Configuration
public class RedisConfig {
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        
        // 使用 StringRedisSerializer 序列化 key
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        
        // 使用 GenericJackson2JsonRedisSerializer 序列化 value,避免 JDK 序列化乱码
        GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer();
        template.setValueSerializer(jsonSerializer);
        template.setHashValueSerializer(jsonSerializer);
        
        template.afterPropertiesSet();
        return template;
    }
}

常用操作示例

java 复制代码
@Service
public class UserService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    // 存储字符串
    public void saveUser(String userId, User user) {
        redisTemplate.opsForValue().set("user:" + userId, user, 1, TimeUnit.HOURS);
    }
    
    // 获取字符串
    public User getUser(String userId) {
        return (User) redisTemplate.opsForValue().get("user:" + userId);
    }
    
    // 操作哈希(适合存储对象字段)
    public void saveUserProfile(String userId, Map<String, Object> profile) {
        redisTemplate.opsForHash().putAll("user:profile:" + userId, profile);
    }
    
    // 操作列表(消息队列)
    public void addMessage(String queue, String message) {
        redisTemplate.opsForList().rightPush(queue, message);
    }
    
    // 操作集合(去重)
    public void addUserTag(String userId, String tag) {
        redisTemplate.opsForSet().add("user:tags:" + userId, tag);
    }
    
    // 操作有序集合(排行榜)
    public void updateScore(String userId, double score) {
        redisTemplate.opsForZSet().add("leaderboard", userId, score);
    }
}
四、补充知识点

序列化器对比

序列化器 适用场景 可读性
StringRedisSerializer 纯字符串 优秀
JdkSerializationRedisSerializer Java 对象 差(乱码)
GenericJackson2JsonRedisSerializer Java 对象 优秀(JSON)

StringRedisTemplate:如果只操作字符串,可以直接用 StringRedisTemplate,它默认已经配置好了字符串序列化器。

缓存注解:Spring Data Redis 还支持 @Cacheable、@CacheEvict 等注解,可以更方便地实现缓存功能。

连接池:生产环境建议配置连接池参数,避免连接泄露。

集群支持:Spring Data Redis 支持 Redis Sentinel 和 Cluster 模式,配置方式略有不同。

相关推荐
SarL EMEN2 小时前
Spring boot创建时常用的依赖
java·spring boot·后端
独断万古他化2 小时前
本地缓存与Redis缓存详解:区别、优缺点及场景选型
数据库·redis·缓存
roamingcode2 小时前
应对 Codex 0.118.0 破坏性更新:Slash Prompt Router 架构解析与实践
java·开发语言·prompt·codex·skill
计算机学姐2 小时前
基于SpringBoot的特色美食分享系统
java·vue.js·spring boot·后端·spring·tomcat·mybatis
计算机学姐2 小时前
基于SpringBoot的在线课程学习网站
java·vue.js·spring boot·后端·学习·spring·intellij-idea
untE EADO2 小时前
Spring Boot从0到1 -day02
java·spring boot·后端
东离与糖宝2 小时前
Spring Boot 3.x面试全攻略:自动配置+事务+AOT,2026最新考点
java·人工智能·面试
梵得儿SHI2 小时前
SpringCloud 秒杀系统生产级落地:Sentinel+Redis 联合优化,从限流防刷到库存闭环,彻底解决超卖 / 宕机 / 恶意刷
redis·spring cloud·sentinel·分布式限流·百万级·瞬时高并发·产级秒杀系统解决方案
1104.北光c°2 小时前
Leetcode146 LRU缓存的三种写法 【hot100算法个人笔记】【java写法】
java·开发语言·笔记·算法·leetcode·hot100·lru缓存