一、添加 redis 起步依赖:
<!-- 添加 redis 起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、启动 redis 测试服务器:
三、在 application.yml 中配置 redis 的连接信息:
四、创建一个 junit 测试程序:
package com.springboot;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.jpa.domain.User;
import com.springboot.jpa.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class RedisTest {
// 在导入 redis 依赖,并且配置 redis 连接信息之后,springboot 会
// 自动帮我们创建一个 redis 模板,存在 ioc 容器中;
// 如果我们需要使用,直接从 IOC 容器中获取即可;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private UserRepository userRepository;
@Test
public void test() throws JsonProcessingException {
// 1、从 redis 中获取缓存数据,数据的形式一般使用 json 字符串
String userListJson = redisTemplate.boundValueOps("users").get();
// 2、判断 redis 中是否存在数据
if (userListJson == null || userListJson.isEmpty()){
// 3、如果不存在,则从数据库中获取数据
List<User> all = userRepository.findAll();
// 4、将数据存储到 redis 缓存中
// 4.1、先将 list 集合数据转换成 json 字符串
ObjectMapper objectMapper = new ObjectMapper();
userListJson = objectMapper.writeValueAsString(all);
// 4.2、再将数据存储到 redis 缓存中
redisTemplate.boundValueOps("users").set(userListJson);
System.out.println("================ 从数据库中获取数据 ================");
}else{
System.out.println("================ 从redis中获取数据 ================");
}
// 4、将数据输出到控制台
System.out.println(userListJson);
}
}
五、第一次测试结果:
Redis 中的数据:
第二次测试结果: