mac-IDEA-SPringBoot(6)-redis

1.在pom.xml中添加起步依赖

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


2.在application.properties里配置redis连接信息

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


3.注入redisTemplate测试redis操作

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class RedisTest {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void test() throws JsonProcessingException {
        //1.redis缓存中得数据
        String userListData = redisTemplate.boundValueOps("user.findAll").get();
        //2.redis中无数据
         if(null==userListData)
         {
            //2.1从数据库获得数据
            List<User> all = userRepository.findAll();
            //2.2转换成json格式字符串
            ObjectMapper om = new ObjectMapper();
            userListData = om.writeValueAsString(all);
            //2.3将数据存储到redis中
            redisTemplate.boundValueOps("user.findAll").set(userListData);
            System.out.println("===从数据库获得数据==========");
        }
      //3.如果有数据 直接读
        else
        {
            System.out.println("===从redis缓存中获得数据=======");
        }

        System.out.println(userListData);

    }

}

 

posted @ 2020-06-10 19:38  jasmineTang  阅读(93)  评论(0)    收藏  举报