SpringBoot-integrate redis

Based on  SpringBoot integration jpa  , we continue to complete SpringBoot integration redis:

 

1. Add the start-up dependency of redis

<!-- 配置使用redis启动器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. Configure redis connection information

Add configuration redis connection information in application.properties:

#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379

3. Test

Open Redis

Write test class:

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

}

 

 

Source code download:  https://pan.baidu.com/s/1-Jo_dqmNvb3QEX8zp4XfkA

Guess you like

Origin blog.csdn.net/weixin_42629433/article/details/84862368