一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java TimedCache 帶時間緩存工具類詳解使用

Java TimedCache 帶時間緩存工具類詳解使用

2022-03-03 00:45劍客阿良_ALiang Java教程

工具類是包含集合框架、遺留的 collection 類、事件模型、日期和時間設施、國際化和各種實用工具類(字符串標記生成器、隨機數生成器和位數組、日期Date類、堆棧Stack類、向量Vector類等)。集合類、時間處理模式、日期工具等各

簡述

我們在工作中會碰到需要使用帶過期時間的緩存場景。但是使用redis有太重了,畢竟緩存的數據很小,放在內存夠夠的。hutools提供了TimedCache時間緩存工具,可以實現該場景。下面使用到該組件,并為了適配工作場景,對該工具類做優化升級。

 

Maven依賴

      <dependency>
          <groupId>cn.hutool</groupId>
          <artifactId>hutool-all</artifactId>
          <version>5.4.6</version>
      </dependency>
      <dependency>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
          <version>30.1.1-jre</version>
      </dependency>

 

簡單使用

不多說了,上代碼。

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.thread.ThreadUtil;

/** @Author huyi @Date 2021/10/12 17:00 @Description: */
public class TimedCacheUtils {
private static final TimedCache<String, String> TIMED_CACHE = CacheUtil.newTimedCache(5000);

static {
  /** 每5ms檢查一次過期 */
  TIMED_CACHE.schedulePrune(5);
}

/**
 * 存入鍵值對,提供消逝時間
 *
 * @param key
 * @param value
 * @param timeout
 */
public static void put(String key, String value, Long timeout) {
  /** 設置消逝時間 */
  TIMED_CACHE.put(key, value, timeout);
}

/**
 * 每次重新get一次緩存,均會重新刷新消逝時間
 * @param key
 * @return
 */
public static String get(String key) {
  return TIMED_CACHE.get(key);
}

public static void main(String[] args) {
  put("haha", "1", 3000L);
  ThreadUtil.sleep(2000);
  //    if (TIMED_CACHE.containsKey("haha")) {
  //      System.out.println("aa");
  //    }
  System.out.println("第1次結果:" + get("haha"));
  ThreadUtil.sleep(2000);
  System.out.println("第2次結果:" + get("haha"));
  ThreadUtil.sleep(5000);
  System.out.println("第3次結果:" + get("haha"));
  // 取消定時清理
  TIMED_CACHE.cancelPruneSchedule();
}
}

首先我們看一下執行的效果

Java TimedCache 帶時間緩存工具類詳解使用

說明:

1、設置的超時時間為3000毫秒,所以第一次打印在2秒鐘,所以可以獲取到值。

2、因為第一次打印調用了get方法,刷新了過期時間,所以依然可以獲取到值。

3、第三次打印在5秒后,所以已經過期,無法獲取到值,打印null。

那么,需要知道是否緩存還在可以使用containsKey方法。如下:

  put("haha", "1", 3000L);
  ThreadUtil.sleep(2000);
  if (TIMED_CACHE.containsKey("haha")) {
    System.out.println("第1次結果:緩存存在");
  }
//    System.out.println("第1次結果:" + get("haha"));
  ThreadUtil.sleep(2000);
  System.out.println("第2次結果:" + get("haha"));
  ThreadUtil.sleep(5000);
  System.out.println("第3次結果:" + get("haha"));
  // 取消定時清理
  TIMED_CACHE.cancelPruneSchedule();

執行結果如下:

Java TimedCache 帶時間緩存工具類詳解使用

 

工具優化-監聽過期、增加回調

我們在使用TimedCache會發現,一旦緩存過期我們并不能立馬知道,很多工作場景中需要對緩存做監聽回調。所以我升級了一下該工具類。

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.thread.ThreadUtil;
import com.google.common.util.concurrent.*;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.text.MessageFormat;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

/** @Author huyi @Date 2021/10/12 10:57 @Description: 時間緩存工具 */
public class TimedCacheUtils {
private static final TimedCache<String, String> TIMED_CACHE = CacheUtil.newTimedCache(5000);
/** 線程池 */
private static final ExecutorService executorService = Executors.newCachedThreadPool();

private static final ListeningExecutorService listeningExecutorService =
    MoreExecutors.listeningDecorator(executorService);
/** 回調方法映射 */
private static ConcurrentHashMap<String, Consumer<String>> callbackMap;

/**
 * 存入鍵值對,添加過期時間,和消費回調
 *
 * @param key
 * @param timeout
 * @param consumer
 */
public static void put(String key, String value, Long timeout, Consumer<String> consumer) {
  TIMED_CACHE.put(key, value, timeout);
  addListen(key, consumer);
}

/**
 * 獲取緩存值
 *
 * @param key
 * @return
 */
public static String get(String key) {
  return TIMED_CACHE.get(key);
}

/**
 * 刪除緩存和回調映射
 *
 * @param key
 */
public static void remove(String key) {
  callbackMap.remove(key);
  TIMED_CACHE.remove(key);
}

/**
 * 添加監聽器
 *
 * @param key
 * @param consumer
 */
public static void addListen(String key, Consumer<String> consumer) {
  ListenableFuture<String> listenableFuture =
      listeningExecutorService.submit(
          () -> {
            while (TIMED_CACHE.containsKey(key)) {
              ThreadUtil.sleep(500);
            }
            return key;
          });
  Futures.addCallback(
      listenableFuture,
      new FutureCallback<String>() {
        @Override
        public void onSuccess(@Nullable String s) {
          consumer.accept(s);
        }

        @Override
        public void onFailure(Throwable throwable) {
          throwable.printStackTrace();
        }
      },
      listeningExecutorService);
}

public static void main(String[] args) {
  put("haha", "1", 3000L, x -> System.out.println(MessageFormat.format("[{0}] - 緩存消逝", x)));
  ThreadUtil.sleep(2000);
  System.out.println(get("haha"));
  ThreadUtil.sleep(2000);
  System.out.println(get("haha"));
  ThreadUtil.sleep(5000);
  System.out.println(get("haha"));
  // 關閉監聽線程池
  listeningExecutorService.shutdown();
}
}

執行結果:

Java TimedCache 帶時間緩存工具類詳解使用

說明:

1、可以看到監聽到緩存過期,并進行了回調。

 

總結

具體的工具類使用場景,因項目而異,大家看著來。

如果本文對你有幫助,請點個贊支持一下吧。

Java TimedCache 帶時間緩存工具類詳解使用

到此這篇關于Java TimedCache 帶時間緩存工具類詳解使用的文章就介紹到這了,更多相關Java TimedCache內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://huyi-aliang.blog.csdn.net/article/details/120727999

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: caoporm碰最新免费公开视频 | 毛片免费网站 | 青青草久| 波多野结衣在线观看中文字幕 | 亚洲成A人片在线观看中文L | 亚洲春色综合另类网蜜桃 | 国产麻豆成91 | 91国产在线第7页 | 男人的天堂comwww | 免费在线视频成人 | 精品国产品国语在线不卡丶 | fuqer日本| 爽好舒服快想要免费看 | 国产在线成人精品 | 九草在线视频 | 色人阁导航 | evelynlin亚裔播放 | 欧美色图亚洲天堂 | 四虎欧美 | 国产精品区一区二区免费 | 嫩草视频在线观看视频播放 | 西野翔全部作品在线观看 | 欧美久久久久久久一区二区三区 | 蛮荒的童话未删减在线观看 | 好男人资源免费观看 | 亚洲精品福利你懂 | 亚洲国产成人综合 | 亚洲激情欧美 | 国产在线观看色 | 美女扒开腿让男人桶爽动态图片 | 色狠狠色狠狠综合天天 | 啾咪成人漫画免费 | 色老板最新网站视频地址 | 白丝校花好湿好紧 | 女人把扒开给男人爽 | 精品久久免费观看 | 国产a一级| 精品免费视在线观看 | 男人猛进女人屁股免费 | 国产hd老头老太婆 | 女人把私密部位张开让男人桶 |