解决Guava Cache存入null值报错的问题

项目背景

  • 最近在做一个给帖子配图的项目,我这里只负责配图,上游将帖子的id发给我,我拿着帖子id去另一个服务查询,但我不能每次都去查人家的服务啊,所以我将每次查到的数据添加到缓存中了.
  • 帖子会有过期的时间,我的上游可能还没收到帖子过期的消息就已经将帖子id发给我了,这时我也需要拿着帖子id去查帖子服务,查不到时我这里就拿到null了,我把查询的结果放到缓存中,当get的时候不就报错了嘛!
private static Cache<String, RawData> tenMiniCache =
      CacheBuilder.newBuilder()
          // 设置缓存初始大小,应该合理设置,后续会扩容
          .initialCapacity(100000)
          // 最大值
          .maximumSize(400000)
          // 并发数设置
          .concurrencyLevel(10)
          .expireAfterWrite(10, TimeUnit.MINUTES)
          // 统计缓存命中率
          .recordStats()
          .build();

RawData contentWtable = null;
                try {
                  contentWtable =
                      tenMiniCache.get(
                          ITEMKEY + itemId,
                          () -> {
                            RawData contentWtableInfo = null;
                            try {
                              contentWtableInfo = speedContentService.getContentWtable(itemId, 1);
                              logger.info(
                                  "speedContentService getContentWtable cost:"
                                      + TimeUtils.diffMs(startTime)
                                      + "-info:"
                                      + JSON.toJSONString(
                                          contentWtableInfo,
                                          SerializerFeature.DisableCircularReferenceDetect));
                            } catch (Exception e) {
                              logger.error(
                                  "featch contentWtable from speedContentService failed,params:"
                                      + itemId
                                      + "-reason:",
                                  e);
                            }
                            return contentWtableInfo;
                          });
                } catch (ExecutionException e) {
                  logger.error(
                      "featch contentWtable from cache failed,params:" + itemId + "-reason:", e);
                  return item;
                }

看这段代码,如果我拿到了null直接顺带存到缓存中,此时就会不停的报错了…

解决方案

  • 那么话又说回来,出了bug就赶紧解决吧,如何解决呢?就需要用到Optional了
  • 建造的cache如下
private static Cache<String, Optional<RawData>> tenMiniCache =
      CacheBuilder.newBuilder()
          // 设置缓存初始大小,应该合理设置,后续会扩容
          .initialCapacity(10)
          // 最大值
          .maximumSize(100)
          // 并发数设置
          .concurrencyLevel(10)
          // 缓存过期时间,写入后1小时 过期
          .expireAfterWrite(10, TimeUnit.MINUTES)
          // 统计缓存命中率
          .recordStats()
          .build();
  • 在功能处实现如下
Optional<RawData> rawDataOptional = null;
try {
  rawDataOptional =
      BaseCacheUtil.getTenMiniCache()
          .get(
              itemId,
              () -> {
                RawData contentWtable = null;
                contentWtable = speedContentService.getContentWtable(itemId, 1);
                logger.info(
                    "speedContentService getContentWtable cost:"
                        + TimeUtils.diffMs(startTime)
                        + "-info:"
                        + JSON.toJSONString(
                            contentWtable,
                            SerializerFeature.DisableCircularReferenceDetect));

                return Optional.ofNullable(contentWtable);
              });
} catch (ExecutionException e) {
  logger.error("get contentWtable from cache is failed!itemId is"+ itemId +"the reason is:", e);
  return item;
}

if (!rawDataOptional.isPresent()) {
  logger.info("get contentWtable from cache is null,by itemId:" + itemId);
  return item;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐观的Terry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值