Springboot/Springcloud项目集成redis进行存取的过程解析
收藏
怎么入门数据库编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《Springboot/Springcloud项目集成redis进行存取的过程解析》,涉及到Redis、存取、SpringcloudSpringboot,有需要的可以收藏一下
前言:Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合),zset(sorted set:有序集合)。
一、redis去官网https://redis.io/download下载后解压
然后点击里面的redis-server.exe(windows平台)即可正常启动
二、在项目中添加redis依赖
org.springframework.boot 。
九、如果想要在单元测试中进行存取
添加测试依赖,Junit必须4.12以上
org.springframework.boot spring-boot-starter-test junit junit 4.12 test在要进行存取的类上添加注解@RunWith、@SpringBootTest,意思是启动单元测试时启动当前项目的启动类,因为启动类里面的@SpringBootApplication里面包含了包扫描@ComponentScan,不然注入StringRedisTemplate或RedisTemplate时注入失败报空指针,当然也可以在启动类里面返回new StringRedisTemplate或new RedisTemplate并且加注解@Bean的方式处理注入失败问题,这里直接通过加注解的方式处理。
@RunWith(value = SpringJUnit4ClassRunner.class) //RedisApp为启动类名字 @SpringBootTest(classes = {RedisApp.class}) public class RedisAppTest { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @Test public void setStringRedis(){ this.stringRedisTemplate.boundValueOps("name2").set("熊大"); System.out.println("ok"); } @Test public void getStringRedis(){ String name = this.stringRedisTemplate.boundValueOps("name2").get(); System.out.println("ok:"+name); } }在redis desktop manager工具中可以看到存储成功了,在控制台也可以读取
九、实际使用思路
@Autowired private RedisTemplate redisTemplate; /** * 首次访问时,如果redis没有数据,就访问数据库,然后把访问到的数据存到redis * 后续访问时,直接查询redis */ @Override public List findByPersonId(Long id) {// 先查看缓存中有没有 List list = (List ) redisTemplate.boundValueOps(id).get(); if(list==null){ System.out.println("redis中没有,开始从数据库中获取"); ......... //查询数据库得到List list =xxxxxx; redisTemplate.boundValueOps(id).set(list);//将从数据库查到的数据添加到redis中以备下次查找 }else{ System.out.println("redis中存在,list是直接从缓存中获取的,没查数据库"); } return list; }