Spring Boot 整合 Redis 使用教程

Redis 是一种高性能的键值存储数据库,常用于缓存、会话管理和消息队列等场景。Spring Boot 通过 Spring Data Redis 提供了简洁的整合方式。


1. 环境准备

1.1 添加依赖

pom.xml 中添加 Redis 依赖(Spring Boot 3.x):

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 若使用 Jedis 客户端 -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

2. 配置 Redis 连接

application.properties 中配置 Redis 连接信息:

properties 复制代码
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.password=  # 若无密码则留空
spring.data.redis.database=0

3. 使用 RedisTemplate 操作 Redis

3.1 注入 RedisTemplate

Spring Boot 自动配置了 RedisTemplate,可直接注入使用:

java 复制代码
@Autowired
private RedisTemplate<String, Object> redisTemplate;

3.2 基础操作示例

java 复制代码
// 存储字符串
redisTemplate.opsForValue().set("name", "Alice");

// 获取字符串
String name = (String) redisTemplate.opsForValue().get("name");
System.out.println("Name: " + name); // 输出: Alice

// 设置过期时间(30秒)
redisTemplate.expire("name", 30, TimeUnit.SECONDS);

// 删除键
redisTemplate.delete("name");

3.3 存储对象(JSON序列化)

默认序列化可能存在问题,建议配置自定义序列化(在配置类中添加):

java 复制代码
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

存储自定义对象:

java 复制代码
User user = new User("Bob", 25);
redisTemplate.opsForValue().set("user:1", user);
User cachedUser = (User) redisTemplate.opsForValue().get("user:1");

4. 使用 Spring Cache 注解

4.1 启用缓存

在启动类添加 @EnableCaching

java 复制代码
@SpringBootApplication
@EnableCaching
public class Application { ... }

4.2 缓存方法结果

java 复制代码
@Service
public class UserService {
    @Cacheable(value = "userCache", key = "#id")
    public User getUserById(String id) {
        // 模拟数据库查询
        return new User(id, "CacheUser", 30);
    }

    @CacheEvict(value = "userCache", key = "#id")
    public void deleteUser(String id) {
        // 删除数据库记录
    }
}

5. 测试 Redis 连接

创建一个简单的测试类:

java 复制代码
@Component
public class RedisTest implements CommandLineRunner {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void run(String... args) {
        redisTemplate.opsForValue().set("testKey", "Hello Redis!");
        String value = redisTemplate.opsForValue().get("testKey");
        System.out.println("Redis测试值: " + value); // 输出: Hello Redis!
    }
}

总结

通过以上步骤即可在 Spring Boot 中快速使用 Redis。关键点:

  1. 配置 Redis 连接信息
  2. 使用 RedisTemplate 进行 CRUD 操作
  3. 通过 @Cacheable 实现声明式缓存

确保本地已启动 Redis 服务(可通过 redis-server 命令启动)。完整代码可参考 Spring Data Redis 官方文档


希望本教程能帮助您快速上手 Redis 整合!如有问题欢迎在评论区留言。

相关推荐
海兰5 分钟前
【第28篇】可观测性实战:LangFuse 方案详解
人工智能·spring boot·alibaba·spring ai
0xDevNull25 分钟前
Linux 中 Nginx 代理 Redis 的详细教程
redis·后端
jinanwuhuaguo44 分钟前
(第三十三篇)五月的文明奠基:OpenClaw 2026.5.2版本的文明级解读
android·java·开发语言·人工智能·github·拓扑学·openclaw
RuoyiOffice1 小时前
SpringBoot+Vue3 企业考勤如何处理法定假期?节假日方案、调休补班与工作日判断链路拆解
spring boot·后端·vue·anti-design-vue·ruoyioffice·假期·人力
xmjd msup1 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
952362 小时前
SpringBoot统一功能处理
java·spring boot·后端
MiNG MENS2 小时前
nginx 代理 redis
运维·redis·nginx
Lyyaoo.2 小时前
优惠券秒杀业务分析
java·开发语言
消失的旧时光-19432 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法
勿忘初心12212 小时前
Java 国密 SM4 加密工具类实战(Hutool + BouncyCastle)|企业级数据加密 + 兼容 JDK8
java·数据安全·数据加密·后端开发·企业级开发·国密 sm4