企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 一.引入依赖 ~~~ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ~~~ ***** ### 二.配置redis连接信息 ~~~ # redis spring: redis: host: 127.0.0.1 port: 6379 ~~~ ### 三.测试 ~~~ package com.youworker; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.youworker.domain.User; import com.youworker.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 javax.annotation.Resource; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Resource private RedisTemplate<String, String> redisTemplate; @Autowired private UserRepository userRepository; @Test public void index() { //将list集合转换成json格式的字符串,使用jackson进行转换 ObjectMapper objectMapper = new ObjectMapper(); //1.从redis中获得得数据,数据的形式json字符串 String userListJson = redisTemplate.boundValueOps("user.findAll").get(); //2.判断redis中是否存在数据 if (null == userListJson) { //3.不存在数据则从数据库查询 List<User> all = userRepository.findAll(); //4.将查询出的数据存储到redis缓存中 try { userListJson = objectMapper.writeValueAsString(all); redisTemplate.boundValueOps("user.findAll").set(userListJson); System.out.println("===========从数据库中获得user的数据==============="); } catch (JsonProcessingException e) { e.printStackTrace(); } } else { System.out.println("===========从redis缓存中获得user的数据==============="); } //5.将数据在控制台打印 System.out.println(userListJson); //json转 对象 User user[] = new User[0]; try { user = objectMapper.readValue(userListJson, User[].class); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println("json转换list"); for (User user1:user){ System.out.println(user1); System.out.println(user1.getUsername()); } } } ~~~