1. Spring Boot 整合 Redis 实战指南
Redis 作为当下最流行的内存数据库之一,在缓存、会话管理、排行榜等场景中发挥着重要作用。作为一名长期使用 Spring Boot 进行企业级开发的工程师,我经常需要在项目中集成 Redis。今天就来分享一下我在实际项目中的整合经验,从环境搭建到核心功能实现,带你避开那些新手容易踩的坑。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境准备与 Redis 安装
2.1 Redis 服务端安装
在开始编码前,我们需要先安装 Redis 服务端。根据不同的操作系统,安装方式略有差异:
Linux 系统(以 Ubuntu 为例)
bash复制sudo apt update
sudo apt install redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server
MacOS 系统
bash复制brew install redis
brew services start redis
Windows 系统
Windows 官方不提供 Redis 原生支持,但可以通过 WSL 或 Docker 方式运行。推荐使用 Docker 方式:
bash复制docker run --name redis -p 6379:6379 -d redis
安装完成后,可以通过以下命令验证 Redis 是否正常运行:
bash复制redis-cli ping
如果返回 "PONG",说明 Redis 服务已成功启动。
提示:生产环境建议配置密码认证和持久化策略,开发环境可以简化配置
2.2 Spring Boot 项目初始化
创建一个新的 Spring Boot 项目时,需要添加以下依赖:
xml复制<dependencies>
<!-- Spring Boot Starter for Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 可选:如果需要使用连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies>
3. Spring Boot 配置 Redis
3.1 基础配置
在 application.properties 或 application.yml 中配置 Redis 连接信息:
properties复制# 基本配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=0
# 认证配置(如果设置了密码)
spring.redis.password=yourpassword
# 连接池配置(推荐生产环境使用)
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-wait=-1ms
YAML 格式的等效配置:
yaml复制spring:
redis:
host: localhost
port: 6379
database: 0
password: yourpassword
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: -1ms
3.2 高级配置
对于生产环境,我们通常需要更细致的配置:
java复制@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, O
