Java本地缓存工具,LoadingCache的使用(附代码) | Java工具类

目录

前言

环境依赖

代码

总结


前言

在工作总常常需要用到缓存,而redis往往是首选,但是短期的数据缓存一般我们还是会用到本地缓存。本文提供一个我在工作中用到的缓存工具,该工具代码为了演示做了一些调整。如果拿去使用的话,可以考虑做成注入Bean对象,看具体需求了。

环境依赖

先添加maven依赖

.

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

代码

不废话,上代码了。

package ai.guiji.csdn.tools;

import cn.hutool.core.thread.ThreadUtil;
import com.google.common.cache.*;
import lombok.extern.slf4j.Slf4j;

import java.text.MessageFormat;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.LongStream;

/** @Author 剑客阿良_ALiang @Date 2021/12/30 17:57 @Description: 缓存工具 */
@Slf4j
public class CacheUtils {

  private static LoadingCache<Long, String> cache;

  /**
   * 初始化缓存方法
   *
   * @param totleCount 缓存池上限
   * @param overtime 超时时间
   * @param unit 时间单位
   * @param handleNotExist 处理不存在key方法
   * @param handleRemove 移除主键消费
   */
  private static void initCache(
      Integer totleCount,
      Integer overtime,
      TimeUnit unit,
      Function<Long, String> handleNotExist,
      Consumer<Long> handleRemove) {
    cache =
        CacheBuilder.newBuilder()
            // 缓存池大小
            .maximumSize(totleCount)
            // 设置时间对象没有被读/写访问则对象从内存中删除
            .expireAfterWrite(overtime, unit)
            // 移除监听器
            .removalListener(
                new RemovalListener<Long, String>() {
                  @Override
                  public void onRemoval(RemovalNotification<Long, String> rn) {
                    handleRemove.accept(rn.getKey());
                  }
                })
            .recordStats()
            .build(
                new CacheLoader<Long, String>() {
                  @Override
                  public String load(Long aLong) throws Exception {
                    return handleNotExist.apply(aLong);
                  }
                });
    log.info("初始化缓存");
  }

  /**
   * 存入缓存
   *
   * @param key 键
   * @param value 值
   */
  public static void put(Long key, String value) {
    try {
      log.info("缓存存入:[{}]-[{}]", key, value);
      cache.put(key, value);
    } catch (Exception exception) {
      log.error("存入缓存异常", exception);
    }
  }

  /**
   * 批量存入缓存
   *
   * @param map 映射
   */
  public static void putMap(Map<Long, String> map) {
    try {
      log.info("批量缓存存入:[{}]", map);
      cache.putAll(map);
    } catch (Exception exception) {
      log.error("批量存入缓存异常", exception);
    }
  }

  /**
   * 获取缓存
   *
   * @param key 键
   */
  public static String get(Long key) {
    try {
      return cache.get(key);
    } catch (Exception exception) {
      log.error("获取缓存异常", exception);
      return null;
    }
  }

  /**
   * 删除缓存
   *
   * @param key 键
   */
  public static void removeKey(Long key) {
    try {
      cache.invalidate(key);
    } catch (Exception exception) {
      log.error("删除缓存异常", exception);
    }
  }

  /**
   * 批量删除缓存
   *
   * @param keys 键
   */
  public static void removeAll(Iterable<Long> keys) {
    try {
      cache.invalidateAll(keys);
    } catch (Exception exception) {
      log.error("批量删除缓存异常", exception);
    }
  }

  /** 清理缓存 */
  public static void clear() {
    try {
      cache.invalidateAll();
    } catch (Exception exception) {
      log.error("清理缓存异常", exception);
    }
  }

  /**
   * 获取缓存大小
   *
   * @return 长度
   */
  public static long size() {
    return cache.size();
  }

  public static void main(String[] args) {
    initCache(
        Integer.MAX_VALUE,
        10,
        TimeUnit.SECONDS,
        k -> {
          log.info("缓存:[{}],不存在", k);
          return "";
        },
        x -> log.info("缓存:[{}],已经移除", x));
    System.out.println(size());
    LongStream.range(0, 10).forEach(a -> put(a, MessageFormat.format("tt-{0}", a)));
    System.out.println(cache.asMap());
    ThreadUtil.sleep(5000);
    LongStream.range(0, 10)
        .forEach(
            a -> {
              System.out.println(get(a));
              ThreadUtil.sleep(1000);
            });
    System.out.println(cache.asMap());
    ThreadUtil.sleep(10000);
    System.out.println(cache.asMap());
  }
}

代码说明

1、在初始化loadingCache的时候,可以添加缓存的最大数量、消逝时间、消逝或者移除监听事件、不存在键处理等等。在上面的代码中,我初始化缓存大小为Integer的最大值,写入10秒后消逝,如不存在key返回空字符串等等。

2、该类也提供了put、putAll、get、remove、removeAll、clear、size方法,可以对缓存进行存、取、删、清理、大小等操作。

3、main演示方法中,先往缓存存入10个数据,然后过5秒后每秒取一个数据,并且打印一下缓存中的全部内容。

4、补充一句LoadingCache是线程安全的哦。

演示一下

15:31:53.495 [main] INFO ai.guiji.csdn.tools.CacheUtils - 初始化缓存
0
15:31:53.502 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[0]-[tt-0]
15:31:53.508 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[1]-[tt-1]
15:31:53.508 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[2]-[tt-2]
15:31:53.508 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[3]-[tt-3]
15:31:53.508 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[4]-[tt-4]
15:31:53.508 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[5]-[tt-5]
15:31:53.508 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[6]-[tt-6]
15:31:53.508 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[7]-[tt-7]
15:31:53.509 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[8]-[tt-8]
15:31:53.509 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存存入:[9]-[tt-9]
{6=tt-6, 5=tt-5, 0=tt-0, 8=tt-8, 7=tt-7, 2=tt-2, 1=tt-1, 9=tt-9, 3=tt-3, 4=tt-4}
tt-0
tt-1
tt-2
tt-3
tt-4
15:32:03.572 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[5],已经移除
15:32:03.573 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[6],已经移除
15:32:03.573 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[5],不存在

15:32:04.581 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[6],不存在

15:32:05.589 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[0],已经移除
15:32:05.589 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[7],已经移除
15:32:05.589 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[8],已经移除
15:32:05.589 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[7],不存在

15:32:06.589 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[8],不存在

15:32:07.591 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[1],已经移除
15:32:07.591 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[2],已经移除
15:32:07.591 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[9],已经移除
15:32:07.591 [main] INFO ai.guiji.csdn.tools.CacheUtils - 缓存:[9],不存在

{6=, 5=, 8=, 7=, 9=}
{}

Process finished with exit code 0
 

可以看到,后面的5-9在内存中已经不存在对应的值了。

总结

本文提供的工具代码主要是为了演示,实际工作中可以按照自己的需求做调整。

 还有补充一下,最近博主在参加评选博客之星活动。如果你喜欢我的文章的话,不妨给我点个五星,投投票吧,谢谢大家的支持!!链接地址:https://bbs.csdn.net/topics/603956455

分享:

        在梦中,我以为人生很漫长,会远得连尽头也看不见,没想到我匆匆翻看,人生,却再也无法逆转。在当下,我以为时间很重,会重得连时针都走不动。 没想到我轻轻一吹,时间,却再也没回来过。——《言叶之庭》

如果本文对你有帮助的话,点个赞吧,谢谢!!

  • 32
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

剑客阿良_ALiang

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

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

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

打赏作者

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

抵扣说明:

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

余额充值