数据库
首页 > 数据库> > Redis缓存查询(防缓存击穿)

Redis缓存查询(防缓存击穿)

作者:互联网

@GetMapping("getResourceByConsumer")
    public APIResponse getResourceByConsumer(String consumerId){
        String error = "";
        try {
            List<TReConsumerResource> resourceByConsumer = new ArrayList<>();
            long startTime = System.currentTimeMillis();
            RedisUtil redisUtil = new RedisUtil(redisTemplate);
            error = "hasKeyPre";
            if(redisUtil.hasKey(consumerId)){
                long getKeyEndTime = System.currentTimeMillis();
                error = "hasKey";
                resourceByConsumer = (List<TReConsumerResource>) redisUtil.get(consumerId);
                error = "redisUtilGet";
                long endTime = System.currentTimeMillis();
                long totalTime = endTime -startTime;
                long getKeyTime = getKeyEndTime - startTime;
                long getValueTime = endTime - getKeyEndTime;
                return new APIResponse(ResponeCode.SUCCESS,
                        "查询成功,通过redis查询,总用时:"+totalTime+"ms 判断redisKey用时:"
                                +getKeyTime+"ms 获取redis值用时"+ getValueTime+"ms"
                        ,resourceByConsumer);
            }else {
                synchronized (this){
                    long getKeyEndTime = System.currentTimeMillis();
                    error = "bySqlPre";
                    resourceByConsumer = tReConsumerResourceService.getResourceByConsumerId(consumerId);
                    error = "bySqlEnd";
                    long getValueEndTime = System.currentTimeMillis();
//            redisUtil.sSetAndTime(consumerId,1L*60L*60L*24L,resourceByConsumer);
                    redisUtil.set(consumerId,resourceByConsumer);
                    long endTime = System.currentTimeMillis();
                    long totalTime = endTime -startTime;
                    long getKeyTime = getKeyEndTime - startTime;
                    long getValueTime = getValueEndTime - getKeyEndTime;
                    long putRedisTime = endTime - getValueEndTime;
                    return new APIResponse(ResponeCode.SUCCESS,
                            "查询成功,通过数据库查询,总用时:"+totalTime+"ms 判断redisKey用时:"
                                    +getKeyTime+"ms 通过数据库获取值用时:"+getValueTime+"ms 放入redis用时:"+putRedisTime+"ms"
                            ,resourceByConsumer);
                }
            }
        }catch (Exception e){
            return new APIResponse(ResponeCode.INTERNAL_SERVER_ERROR,e.getMessage()+error);
        }

标签:缓存,Redis,击穿,System,long,consumerId,ms,error,resourceByConsumer
来源: https://www.cnblogs.com/ideaAI/p/16667421.html