首页 > 数据库 >springboot 集成redis

springboot 集成redis

时间:2022-11-07 17:45:44浏览次数:40  
标签:集成 缓存 springboot redis UserOne getAll2 userListJsonStr List

1、redis for windows 下载地址 : https://how2j.cn/frontdownload?bean.id=1733 (注意启动方式)

2、使用场景:高频访问的场景:--- 用户的权限可以放到缓存中设置过期时间(就不考虑数据变化了)(可以使用fastJson把方法作为键)

3、核心思想-->修改查询的方法--- if (缓存有该键 ){输出值} else{ sql查询  --存入缓存}

 

        依赖 
     <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--fastjson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.41</version> </dependency>

yml配置 :

redis:
port: 6379
host: 127.0.0.1

 

 

核心代码  

@Override
    public List<UserOne> getAll2() {
       
        String userListJsonStr = redisTemplate.opsForValue().get("UserOneService.getAll2");
        if ( userListJsonStr!=null && !userListJsonStr.isEmpty()) {
            List<UserOne> UserOne = JSON.parseArray(userListJsonStr, UserOne.class);
            log.info("读缓存");
            return UserOne;
        }
        else {
            List<UserOne> all = userOneMapper.getAll();

            redisTemplate.opsForValue().set("UserOneService.getAll2",JSON.toJSONString(all),2, TimeUnit.HOURS);
            log.info("读数据库-----存入缓存");
            return all;
        }
    }      

标签:集成,缓存,springboot,redis,UserOne,getAll2,userListJsonStr,List
From: https://www.cnblogs.com/demoyaya/p/16862445.html

相关文章