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);
        }

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/288222.html

(0)
上一篇 2022年9月8日
下一篇 2022年9月8日

相关推荐

发表回复

登录后才能评论