SpringBoot集成redis
·
在SpringBoot中集成redis较为简单,具体步骤如下(也可以通过快速配置选择redis,这样就不用自己配置什么东西了)
- 新建一个SpingBoot web工程
应该都会 - 新建一个配置文件,这里新建一个application.yml文件
- 添加redis配置信息(本人设置了密码,没有设置密码的可以不添加password)
host和port都有默认值,host的默认值是localhost(相当于127.0.0.1),port的值是6379,在本机使用可以不添加这个配置信息

- 编写一个测试类(数据库配置不在本章范围之内,我是使用的mybatis)
当第一次运行的时候,在redis中找不到对应的key,此时就会去数据库中查询数据并报错到redis缓存当中import cn.oopeak.boot.MySpringBootApplication; import cn.oopeak.boot.mapper.PersonMapper; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; 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; @RunWith(SpringRunner.class) @SpringBootTest(classes = MySpringBootApplication.class) public class SpringTest { @Autowired private PersonMapper personMapper; @Autowired private RedisTemplate<String, String> redisTemplate; @Test public void aa() { //底层还是在调用opsFor....方法 String strings = redisTemplate.boundValueOps("person.test1").get(); //如果在redis中没有找到,就到数据库中查询,然后保存到到redis中 if (strings == null) { System.out.println("在redis没有找到"); //json工具类 ObjectMapper objectMapper = new ObjectMapper(); try { //writeValueAsString方法是将一个Object对象转换成字符串 //personMapper.queryAll()返回的是一个list集合 strings = objectMapper.writeValueAsString(personMapper.queryAll()); System.out.println(strings); //保存到redis中 redisTemplate.boundValueOps("person.test1").set(strings); } catch (JsonProcessingException e) { e.printStackTrace(); } } else { System.out.println("在redis中找到了 哈哈哈哈"); System.out.println(redisTemplate.opsForValue().get("person.test1")); } } }
第一次运行截图
在后面的运行中,都会直接从redis中查找数据
第二次运行截图

查看reids管理工具(RedisDesktopManager)可以发现redis缓存当中已经存在

更多推荐


所有评论(0)