1. 添加依赖
在 pom.xml
中引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置连接信息
在 application.yml
中配置 Redis:
spring:
redis:
host: 127.0.0.1 # Redis 服务器IP
port: 6379 # 端口
password: yourpassword # 密码(若无则省略)
database: 0 # 默认数据库索引
3. 使用 RedisTemplate 操作
注入 RedisTemplate
直接读写数据:
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 写入数据
redisTemplate.opsForValue().set("key", "value");
// 读取数据
String value = (String) redisTemplate.opsForValue().get("key");
4. 进阶用法
(1) 存储对象(需序列化)
// 实体类实现 Serializable 接口
public class User implements Serializable {
private String name;
private Integer age;
}
// 存储对象
User user = new User("Alice", 30);
redisTemplate.opsForValue().set("user:1", user);
(2) 设置过期时间
redisTemplate.opsForValue().set("token", "abc123", 30, TimeUnit.MINUTES); // 30分钟后过期
5. 生产环境建议
连接池配置(在
application.yml
中增加):spring: redis: lettuce: pool: max-active: 8 # 最大连接数 max-idle: 4 # 最大空闲连接 min-idle: 1 # 最小空闲连接
- 启用缓存注解:
在启动类加@EnableCaching
,在方法上使用@Cacheable
自动缓存结果。
完整代码示例
@SpringBootApplication
@EnableCaching // 启用缓存
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
@Service
public class UserService {
@Cacheable(value = "users", key = "#id") // 自动缓存查询结果
public User getUserById(String id) {
// 模拟数据库查询
return new User(id, "Tom", 25);
}
}