千家信息网

Java本地缓存工具LoadingCache怎么使用

发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,这篇文章主要介绍"Java本地缓存工具LoadingCache怎么使用",在日常操作中,相信很多人在Java本地缓存工具LoadingCache怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好
千家信息网最后更新 2026年11月01日Java本地缓存工具LoadingCache怎么使用

这篇文章主要介绍"Java本地缓存工具LoadingCache怎么使用",在日常操作中,相信很多人在Java本地缓存工具LoadingCache怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Java本地缓存工具LoadingCache怎么使用"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

环境依赖

先添加maven依赖

                    com.google.guava            guava            30.1.1-jre                            cn.hutool            hutool-all            5.5.2                            org.projectlombok            lombok            true        

代码

不废话,上代码了。

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: 缓存工具 */@Slf4jpublic class CacheUtils {   private static LoadingCache cache;   /**   * 初始化缓存方法   *   * @param totleCount 缓存池上限   * @param overtime 超时时间   * @param unit 时间单位   * @param handleNotExist 处理不存在key方法   * @param handleRemove 移除主键消费   */  private static void initCache(      Integer totleCount,      Integer overtime,      TimeUnit unit,      Function handleNotExist,      Consumer handleRemove) {    cache =        CacheBuilder.newBuilder()            // 缓存池大小            .maximumSize(totleCount)            // 设置时间对象没有被读/写访问则对象从内存中删除            .expireAfterWrite(overtime, unit)            // 移除监听器            .removalListener(                new RemovalListener() {                  @Override                  public void onRemoval(RemovalNotification rn) {                    handleRemove.accept(rn.getKey());                  }                })            .recordStats()            .build(                new CacheLoader() {                  @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 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 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在内存中已经不存在对应的值了。

到此,关于"Java本地缓存工具LoadingCache怎么使用"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

缓存 工具 方法 大小 时间 学习 代码 最大 内存 对象 数据 更多 处理 帮助 演示 监听 实用 安全 接下来 上代 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 互联网金融科技 互联网科技官网 科技互联网政务服务 米客互联网科技 成都狮子座互联网科技 丰台科技园 互联网公司 华脉科技工业互联网产品 太原新华互联网科技学校怎么样 互联网公司会议桌创意科技软装饰 现代科技和互联网有关系吗 阿里巴巴算科技企业还是互联网 湖北码尼互联网科技有限公司电话 青岛科技大学互联网大赛研究生 想开互联网科技公司怎么样 城市宝互联网科技有限公司 互联网领先科技宣传片 工业互联网科技创业 互联网科技手机排行榜 同城互联网络科技 广东猫王互联网科技有限公司电话 湖南永感互联网科技有限公司 电子科技大学互联网 上海卓越科技 互联网 贵州叶脉互联网科技有限公司所属行业 互联网还是高科技吗 千方科技属于互联网企业吗 移动互联网年度科技创新 保险科技服务互联网营销体系 互联网时代科技型公司的机会 求路客互联网科技电话
0