SpringBoot学习笔记(十):SpringBoot 集成 redis


接上一篇 SpringBoot学习笔记(八):SpringBoot 整合 jpa,在 jpa 项目上集成 redis:


一、添加 redis 起步依赖:

        <!-- 添加 redis 起步依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

二、启动 redis 测试服务器:

三、在 application.yml 中配置 redis 的连接信息:

四、创建一个 junit 测试程序:

package com.springboot;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.jpa.domain.User;
import com.springboot.jpa.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;

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

    // 在导入 redis 依赖,并且配置 redis 连接信息之后,springboot 会
    // 自动帮我们创建一个 redis 模板,存在 ioc 容器中;
    // 如果我们需要使用,直接从 IOC 容器中获取即可;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test() throws JsonProcessingException {
        // 1、从 redis 中获取缓存数据,数据的形式一般使用 json 字符串
        String userListJson = redisTemplate.boundValueOps("users").get();

        // 2、判断 redis 中是否存在数据
        if (userListJson == null || userListJson.isEmpty()){

            // 3、如果不存在,则从数据库中获取数据
            List<User> all = userRepository.findAll();

            // 4、将数据存储到 redis 缓存中
            // 4.1、先将 list 集合数据转换成 json 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            userListJson = objectMapper.writeValueAsString(all);

            // 4.2、再将数据存储到 redis 缓存中
            redisTemplate.boundValueOps("users").set(userListJson);

            System.out.println("================ 从数据库中获取数据 ================");
        }else{
            System.out.println("================ 从redis中获取数据 ================");
        }

        // 4、将数据输出到控制台
        System.out.println(userListJson);
    }
}

五、第一次测试结果:

Redis 中的数据:

第二次测试结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值