SpringBoot整合Redis

返回上一级目录   

本页源码参考:源码免费下载 免费在线查看

①添加redis的起步依赖

②配置redis的连接信息

③注入RedisTemplate测试redis操作 

④打印结果


 

不重新创建项目了,在springboot_springdataJPA中添加Redis完成

①添加redis的起步依赖

 
        
            org.springframework.boot
            spring-boot-starter-data-jpa
            2.1.9.RELEASE
        


②配置redis的连接信息

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


③注入RedisTemplate测试redis操作
 

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class TestRedis{
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void test() throws JsonProcessingException {
        //从redis缓存中获得指定的数据
        String userListData = redisTemplate.boundValueOps("user.findAll").get();
        //如果redis中没有数据的话
        if(null==userListData){
            //查询数据库获得数据
            List all = userRepository.findAll();
            //转换成json格式字符串
            ObjectMapper om = new ObjectMapper();
            userListData = om.writeValueAsString(all);
            //将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库
            redisTemplate.boundValueOps("user.findAll").set(userListData);
            System.out.println("===============从数据库获得数据===============");
        }else{
            System.out.println("===============从redis缓存中获得数据===============");
        }
        System.out.println(userListData);
    }
}

④打印结果

你可能感兴趣的:(Spring,Boot)