一、引言
Redis 是一个开源的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中介。在现今的高并发、大数据量的互联网应用中,Redis 的作用愈发重要。Spring Boot 提供了对 Redis 的集成支持,使得开发者可以更加便捷地在项目中集成 Redis。
二、环境准备
在开始之前,请确保你的系统中已经安装了 Redis,并且 Redis 服务正在运行。
Redis 安装可以参考:Redis 实战 – Redis 安装
三、添加依赖
在 Spring Boot 项目的 pom.xml 文件中,添加 Redis 的相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
四、配置 Redis
在 application.yml 文件中,配置 Redis 的相关信息:
# Spring Boot Redis 配置
spring:
redis:
# Redis 数据库索引(默认为0)
# 如果在 Redis 中配置了多个数据库,可以通过修改这个值来选择不同的数据库
database: 0
# Redis 服务器地址
host: localhost
# Redis 服务器连接端口
# Redis 默认端口是 6379
port: 6379
# Redis 服务器连接密码(默认为空)
password:
# Jedis 连接池配置
jedis:
pool:
# 连接池中的最大活跃连接数
# 设置为 8 表示同一时间最多有 8 个连接被使用
max-active: 8
# 连接池中的最大等待时间(毫秒)
# 当连接池中没有可用连接时,新的请求会等待这个时间,单位毫秒
# -1 表示无限等待
max-wait: -1ms
# 连接池中的最大空闲连接数
# 空闲连接指的是那些没有被使用的连接
max-idle: 8
# 连接池中的最小空闲连接数
# 当空闲连接数少于这个数时,连接池会创建新的连接
min-idle: 0
# 连接超时时间(毫秒)
# 当尝试连接 Redis 服务器时,如果在这个时间内没有连接成功,会抛出异常
timeout: 5000
五、使用 RedisTemplate
Spring Boot 提供了 RedisTemplate 来操作 Redis,可以直接注入使用。下面是一个简单的示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Autowired
private 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);
}
// ... 其他 Redis 操作方法
}
六、自定义序列化器
默认情况下,RedisTemplate 使用 JDK 序列化器,这可能会导致存储的数据体积较大。在实际开发中,可能会希望使用其他序列化器,如 JSON。以下是一个自定义 JSON 序列化器的示例:
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.activateDefaultTyping( LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
// 空字段不序列化
om.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
// 解决jackson2无法反序列化LocalDateTime的问题
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
om.registerModule(new JavaTimeModule());
jsonRedisSerializer.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jsonRedisSerializer);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
//设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
有关序列化知识,可以参考:序列化与消息转换器
七、测试
最后,可以在 Spring Boot 项目中编写测试用例或直接在 Controller 中使用 RedisService
来测试 Redis 的集成情况。
八、总结
Spring Boot 集成 Redis 非常简单,只需要添加依赖、配置 Redis 和使用 RedisTemplate
即可。通过自定义序列化器,可以更加灵活地控制数据的存储格式
九、Springboot 中 使用 Redis 缓存 Session 信息
待更新