上一次已经成功使用MySQL数据库连接了Springboot项目
这次尝试使用另外的数据库进行保存和数据的加载
尝试连接Redis数据库!
首先下载安装redis数据库,一定记得下载windows版!去安装目录下,输入cmd打开终端,输入redis-server.exe redis.windows.conf
启动redis服务
添加Redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在application.properties中添加以下依赖,密码没有设置
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.password=
删除了在MySQL数据库中使用的GameRecordRepository类,重新创建了RedisService类,代码如下所示(@Component和@Autowired为什么会写,后面有解释)
package org.example.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
@Component
public class RedisService {
private final RedisTemplate<String, Object> redisTemplate;
@Autowired
public RedisService(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
// 获取数据
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
// 存储数据
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
// 存储数据并设置过期时间
public void set(String key, Object value, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, value, timeout, unit);
}
// 删除数据
public void delete(String key) {
redisTemplate.delete(key);
}
}
但运行之后却报了以下的错:
首先我查原因查到是因为这个Spring Boot 应用启动时无法找到 RedisTemplate
类型的 Bean,而 RedisService
类的构造函数需要这个 Bean。于是在在 RedisService
类里,构造函数使用了 @Autowired
注解来自动注入 RedisTemplate<String, Object>
类型的 Bean。并且重新创建了RedisConfig类,代码如下所示:
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 redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 设置键的序列化器
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
// 设置值的序列化器
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
但重新启动之后还是报错
查了原因之后发现是因为我的redis数据库服务没开启,我就感觉不对,明明之前确认过开启了的,后面搜了之后才知道原来在使用redis数据库的时候,那个终端页面不能关闭,于是重新进到redis的目录下重新启动了redis数据库的服务。
项目结构如图所示:
可以启动成功了!由于实现效果和上次的MySQL一样,于是在这里我就简单附几张图
保存数据功能:
读取数据功能:
到这里就完成了!