Solo  当前访客:1 开始使用


java实现本地缓存

手写本地缓存考虑的点:过期时间、如何清除过期的缓存、缓存数据的大小

    /**
     * 缓存数据Map
     */
    private static final Map<String, MyCache> CACHE_MAP = new ConcurrentHashMap<>();
 
    /**
     * 定时器线程池,用于清除过期缓存
     */
    private static final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
 
    static {
        // 注册一个定时线程任务,服务启动1秒之后,每隔500毫秒执行一次
        // 定时清理过期缓存
        executorService.scheduleAtFixedRate(CacheUtil::clearCache, 1000, 500, TimeUnit.MILLISECONDS);
    }

解释:

用Map作为数据缓存的容器;用 ScheduledExecutorService 定时器线程池去做按指定的频率做数据的清除工作


使用第三方缓存

Guava Cache

    @Test
    void testGuava() throws ExecutionException, InterruptedException {
        // 创建一个缓存实例
        Cache<String, String> cache = CacheBuilder.newBuilder()
                // 初始容量
                .initialCapacity(5)
                // 最大缓存数,超出淘汰
                .maximumSize(10)
                // 过期时间 设置写入3秒后过期
                .expireAfterWrite(3, TimeUnit.SECONDS)
                .build();
 
        // 写入缓存数据
        cache.put("name", "qq");
 
        // 读取缓存数据
        String value1 = cache.get("name", () -> "key过期");
        System.out.println("第一次查询结果:" + value1);
 
        // 停顿4秒
        TimeUnit.SECONDS.sleep(4);
 
 
        // 读取缓存数据
        String value2 = cache.get("name", () -> "key过期");
        System.out.println("第二次查询结果:" + value2);
    }

标题:java实现本地缓存
作者:temp12138
地址:https://solo.mfyzl.icu/articles/2024/03/22/1711086148826.html

标签:
新一篇: 关于B树索引 旧一篇: 触发Boss单日聊天上限