在SSM中使用Redis缓存数据库

首先在pom文件中添加以下坐标

<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


在启动类添加
@Bean
public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}

然后写一个定时任务对数据库进行同步,

// 定时功能
@Scheduled(fixedRate = 1 * 30 * 1000)
public void syncBookTags() {
log.debug("执行BookTag储存: {}", LocalDateTime.now());
// 调用URL获取Tag内容
String url = "http://api-book/v1/bookTag/readAll";
BookTagVo[] bookTags = restTemplate.getForObject(url, BookTagVo[].class);
// 通过RedisTemplate获取List类型数据List类型数据的操作器
ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
// 通过RedisTemplate获取一般类型数据的操作器
ValueOperations<String, Serializable> opsForValue = redisTemplate.opsForValue();
// 在Redis中用于保存标签列表数据的Key
String tagsKey = "bookTags";
// 先删除Redis服务器中已经保存的标签列表
redisTemplate.delete(tagsKey);
// 通过以上操作器向Redis中写入标签列表,每次只能写入List中的1条标签数据
for (BookTagVo tag : bookTags) {
// 向List中存入当前标签数据
opsForList.rightPush(tagsKey, tag);
// 将当前标签数据单独的存为Redis中的1个数据
String key = "bookTags" + tag.getId();
opsForValue.set(key, tag);
}
}

// 注意以上使用了RestTemplate对微服务进行访问并获得需要的内容,可以根据业务需要,直接对数据库进行查询获得数据

以上则完成对数据的保存

查询的时候可以通过控制器(Controller)进行查询
@Autowired
RedisTemplate<String, Serializable> redisTemplate;

@GetMapping("/readAll")
public ResultBean<List<BookTag>> readBookTagAll(){
// 通过RedisTemplate获取List类型数据的操作器
ListOperations<String, Serializable> ops = redisTemplate.opsForList();
// 在Redis中用于保存标签列表数据的Key
String tagsKey = "bookTags";
// 获取数据
long start = 0;
long end = ops.size(tagsKey);
List<Serializable> list = ops.range(tagsKey,start,end);
// 返回
return ResultBean.ok(list);
}

当然将查询功能封装起来更好

以上则简单初步的完成将数据存入Redis并取出



 


posted @ 2021-08-14 15:07  daoyih  阅读(255)  评论(0)    收藏  举报