Spring Boot集成Redis实现数据持久化
在之前的项目中,已经实现了基于MySQL的数据持久化方案。本次将改用Redis这种内存数据库来完成游戏数据的保存与读取功能。
环境准备
首先需要获取Redis服务。Windows用户需要下载Windows版本的Redis。安装完成后,在Redis安装目录下打开命令提示符,执行以下命令启动服务:
redis-server.exe redis.windows.conf
服务启动后不要关闭终端窗口,否则Redis服务将停止。
添加项目依赖
在pom.xml文件中添加Spring Data Redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置文件
在application.properties中配置Redis连接参数:
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.password=
由于是本地开发环境,密码字段保持为空。
Redis配置类
为了确保RedisTemplate能够正确序列化数据,需要创建配置类来自定义RedisTemplate的行为:
package org.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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// 配置键的序列化方式
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
// 配置值的序列化方式
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
这个配置类会创建一个RedisTemplate实例,键使用字符串序列化,值使用JSON序列化,这样可以方便地存储和读取Java对象。
数据操作服务类
创建服务类来处理具体的业务逻辑:
package org.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class DataStorageService {
private final RedisTemplate<String, Object> dataStore;
@Autowired
public DataStorageService(RedisTemplate<String, Object> dataStore) {
this.dataStore = dataStore;
}
public Object retrieve(String key) {
return dataStore.opsForValue().get(key);
}
public void store(String key, Object value) {
dataStore.opsForValue().set(key, value);
}
public void storeWithExpiration(String key, Object value, long duration, TimeUnit unit) {
dataStore.opsForValue().set(key, value, duration, unit);
}
public void remove(String key) {
dataStore.delete(key);
}
}
服务类提供了retrieve、store、storeWithExpiration和remove四个方法,分别用于数据的读取、存储、带过期时间的存储和删除操作。
常见问题解决
首次启动项目时,可能会遇到以下错误:应用无法找到RedisTemplate类型的Bean。这是因为虽然添加了Redis依赖,但如果没有显式配置,Spring容器不会自动创建RedisTemplate实例。解决方法就是添加上述RedisConfig配置类。
另一个常见问题是Redis服务未启动。如果连接失败,应检查Redis服务器是否正在运行。特别需要注意的是,Redis终端窗口必须保持打开状态,关闭终端会导致服务停止。
完成上述配置后,数据保存和读取功能即可正常工作。