基于 SpringBoot 集成 jpa , 我们继续完成 SpringBoot 集成 redis:
一. 添加redis的起步依赖
<!-- 配置使用redis启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二. 配置redis的连接信息
在 application.properties 中加入配置redis的连接信息:
#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
三. 测试
开启 Redis
编写测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJpaApplicationTests {
@Autowired
private UserRepository userRepository;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void testRedis() throws JsonProcessingException {
//1、从redis中获得数据 数据的形式json字符串
String userListJson = redisTemplate.boundValueOps("user.findAll").get();
//2、判断redis中是否存在数据
if (null == userListJson) {
//3、不存在数据 从数据库查询
List<User> all = userRepository.findAll();
//4、将查询出的数据存储到redis缓存中
//向将list集合转换成json格式的字符串 使用jackson进行转换
ObjectMapper objectMapper = new ObjectMapper();
userListJson = objectMapper.writeValueAsString(all);
redisTemplate.boundValueOps("user.findAll").set(userListJson);
System.out.println("=======从数据库中获得user的数据======");
} else {
System.out.println("=======从redis缓存中获得user的数据======");
}
//4、将数据在控制台打印
System.out.println(userListJson);
}
}
源代码下载: https://pan.baidu.com/s/1-Jo_dqmNvb3QEX8zp4XfkA