package com.hope;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hope.domain.User;
import com.hope.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;
/**
* @author newcityman
* @date 2020/1/19 - 23:20
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class RedisTest {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private UserRepository userRepository;
@Test
public void test() throws JsonProcessingException {
//1、从redis中获取数据,数据形式是json
String userListJson = redisTemplate.boundValueOps("user.findAll").get();
//2、判断redis中是否存在
if(null==userListJson){
//3、如果不存在,从数据库中查询
List<User> list = userRepository.findAll();
//4、将查出的数据存放到redis中
ObjectMapper objectMapper = new ObjectMapper();
userListJson = objectMapper.writeValueAsString(list);
redisTemplate.boundValueOps("user.findAll").set(userListJson);
System.out.println("========从数据库中获取数据存入缓存========");
}else{
System.out.println("========从redis缓存中获取数据========");
}
//5、将数据在控制台打印
System.out.println(userListJson);
}
}