栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

目录

前言

环境依赖

代码

总结


前言

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

环境依赖

先添加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;


@Slf4j
public class CacheUtils {

  private static LoadingCache cache;

  
  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("初始化缓存");
  }

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

  
  public static void putMap(Map map) {
    try {
      log.info("批量缓存存入:[{}]", map);
      cache.putAll(map);
    } catch (Exception exception) {
      log.error("批量存入缓存异常", exception);
    }
  }

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

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

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

  
  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

分享:

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/685328.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号