首页 > 数据库 >springboot中如何向redis缓存中存入数据

springboot中如何向redis缓存中存入数据

时间:2022-12-04 11:57:16浏览次数:37  
标签:缓存 springboot redis springframework org import com userListJson

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);
}
}

标签:缓存,springboot,redis,springframework,org,import,com,userListJson
From: https://www.cnblogs.com/codeLearn/p/16949584.html

相关文章