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

相关推荐
独泪了无痕3 小时前
探索Pinyin4j-Java中的拼音转换利器
java·后端
道尔柯南4 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
kingx35 小时前
Bugku 3122 谷歌小恐龙题解:纯离线逆向 Vault 的 AES-GCM 加密资源(附 Python 解密器)
java·逆向·ctf·bugku·aes-gcm
翔云1234567 小时前
RocksDB中,客户端每写入一次数据,需要访问几次磁盘
运维·数据库·mysql
DevOpenClub7 小时前
职教高考控制线 API:招生类别枚举、筛选与空分数含义
java·数据库·高考
aiks_yuan8 小时前
Token 放 Redis 还是用 JWT:Java 实测验签和查 Redis 耗时,退出登录、改密码踢下线怎么做(jjwt 0.12 + Redis 7.2)
redis
露天赏雪8 小时前
第3篇:Sentinel熔断降级实战:大模型接口抖动时的服务兜底方案
java·开发语言·人工智能·spring boot·spring·servlet·sentinel
天天被压力8 小时前
【A股分钟级高频数据完全手册 #06】北交所分钟级数据接口:京市股票Pro版最新分时
java·人工智能·python
天天被压力8 小时前
【A股分钟级高频数据完全手册 #05】指数历史分钟数据接口:Pro版沪深指数分时回放
java·人工智能·python
captain3768 小时前
▲统一功能——DispatcherServlet源码分析
java·spring·java-ee·log4j·maven