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 整合!如有问题欢迎在评论区留言。

相关推荐
unique_perfect11 分钟前
vue2与springboot实现deepseek打印机聊天
spring boot·websocket·ai·vue2·deepseek
java1234_小锋15 分钟前
Spring IoC的实现机制是什么?
java·后端·spring
xqqxqxxq1 小时前
背单词软件技术笔记(V2.0扩展版)
java·笔记·python
消失的旧时光-19431 小时前
深入理解 Java 线程池(二):ThreadPoolExecutor 执行流程 + 运行状态 + ctl 原理全解析
java·开发语言
哈哈老师啊1 小时前
Springboot学生综合测评系统hxtne(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot
4311媒体网1 小时前
帝国cms调用文章内容 二开基本操作
java·开发语言·php
小小8程序员1 小时前
Redis-10
数据库·redis·缓存
梁萌1 小时前
MySQL数据库分库分表介绍
数据库·mysql·shardingsphere·分库分表
zwxu_1 小时前
Nginx NIO对比Java NIO
java·nginx·nio
前端小端长2 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring