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


    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);
    }
    }
  • 相关阅读:
    一个强大的在线开发IDE: CodeRun Studio
    PyQuery: 一个类似jQuery的Python库
    jQuery的图片剪切插件
    SVN导出两个版本之间的差异文件
    javascript中的focus()光标定位
    零分,裸奔真危险
    Django 截取中英文混合字符串
    360与金山网盾
    20100301:IE6的葬礼
    两个与jQuery相关的资源:导航条与提示
  • 原文地址:https://www.cnblogs.com/newcityboy/p/12216029.html
Copyright © 2020-2023  润新知