1. 添加依赖
在项目的 pom.xml
文件中添加 Spring Data Redis 的依赖。Spring Boot 提供了 spring-boot-starter-data-redis
,它默认使用 Lettuce 作为 Redis 客户端。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
如果需要使用 Jedis 作为客户端,可以排除 Lettuce 并添加 Jedis 依赖。
2. 配置 Redis 连接
在 application.yml
或 application.properties
文件中配置 Redis 的连接信息。
application.yml 示例:
spring:redis:host: 127.0.0.1 # Redis 服务器地址port: 6379 # Redis 服务器端口password: # Redis 密码(如果有)database: 0 # 数据库索引(默认为0)timeout: 1800000 # 连接超时时间(毫秒)lettuce:pool:max-active: 20 # 连接池最大连接数max-wait: -1 # 最大阻塞等待时间(负数表示无限制)max-idle: 5 # 最大空闲连接数min-idle: 0 # 最小空闲连接数
从 Spring Boot 2.x 开始,推荐使用 spring.data.redis
配置方式。
3. 创建 Redis 配置类
创建一个配置类来定义 RedisTemplate
,并设置序列化器。
package com.example.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);template.setKeySerializer(new StringRedisSerializer()); // 设置键的序列化器template.setValueSerializer(new StringRedisSerializer()); // 设置值的序列化器return template;}
}
4. 编写 Redis 操作类
创建一个服务类来封装 Redis 的常用操作。
package com.example.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;@Service
public class RedisService {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;public void setValue(String key, Object value) {redisTemplate.opsForValue().set(key, value);}public Object getValue(String key) {return redisTemplate.opsForValue().get(key);}public void deleteValue(String key) {redisTemplate.delete(key);}
}
5. 使用 Redis
在业务逻辑中注入 RedisService
或直接使用 RedisTemplate
来操作 Redis。
6. 启动并测试
启动 Spring Boot 应用程序后,可以通过编写测试代码或使用工具(如 Postman)验证 Redis 的操作是否成功。