Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use TimedCache with time caching utility class in Java

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "Java TimedCache with time cache tool class how to use", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn "Java with time cache tool class how to use" this article.

Brief introduction

We will encounter cache scenarios that need to be used with expiration time in our work. But the use of redis is too heavy, after all, the cached data is very small, enough memory. Hutools provides a TimedCache time caching tool to implement this scenario. Use this component below, and optimize and upgrade the tool class in order to adapt to the work scenario.

Maven relies on cn.hutool hutool-all 5.4.6 com.google.guava guava 30.1.1-jre for easy use

Say no more. Code it.

Import cn.hutool.cache.CacheUtil;import cn.hutool.cache.impl.TimedCache;import cn.hutool.core.thread.ThreadUtil; / * * @ Author huyi @ Date 17:00 on 2021-10-12 @ Description: * / public class TimedCacheUtils {private static final TimedCache TIMED_CACHE = CacheUtil.newTimedCache (5000); static {/ * * Expiration per 5ms * / TIMED_CACHE.schedulePrune (5) } / * store key-value pairs to provide elapsed time * * @ param key * @ param value * @ param timeout * / public static void put (String key, String value, Long timeout) {/ * * set elapsed time * / TIMED_CACHE.put (key, value, timeout) } / * * each time the cache is re-get, the elapsed time will be refreshed * @ param key * @ return * / public static String get (String key) {return TIMED_CACHE.get (key);} public static void main (String [] args) {put ("", "1", 3000L); ThreadUtil.sleep (2000) / / if (TIMED_CACHE.containsKey ("")) {/ / System.out.println ("aa"); / /} System.out.println ("first result: + get (" ")); ThreadUtil.sleep (2000); System.out.println (" second result: + get ("")); ThreadUtil.sleep (5000) System.out.println ("3rd result:" + get ("")); / / cancel scheduled cleaning of TIMED_CACHE.cancelPruneSchedule ();}}

First of all, let's take a look at the effect of implementation.

Description:

1. The timeout set is 3000 milliseconds, so the first print is 2 seconds, so you can get the value.

2. Because the get method is called on the first print, the expiration time is refreshed, so the value can still be obtained.

3, the third print in 5 seconds later, so it has expired, can not get the value, print null.

Then you need to know if the cache is still available to use the containsKey method. As follows:

Put ("", "1", 3000L); ThreadUtil.sleep (2000); if (TIMED_CACHE.containsKey ("")) {System.out.println ("first result: cache presence");} / / System.out.println ("first result: + get (" ")); ThreadUtil.sleep (2000); System.out.println (" second result: "+ get (" ")) ThreadUtil.sleep (5000); System.out.println ("3rd result:" + get ("")); / / cancel scheduled cleaning TIMED_CACHE.cancelPruneSchedule ()

The implementation results are as follows:

Tool optimization-monitor expiration, add callback

When we use TimedCache, we will find that once the cache expires, we can't immediately know that we need to monitor the cache callback in many work scenarios. So I upgraded the tool class.

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 10:57 @ Description on 2021-10-12: time caching tool * / public class TimedCacheUtils {private static final TimedCache TIMED_CACHE = CacheUtil.newTimedCache (5000); / * Thread Pool * / private static final ExecutorService executorService = Executors.newCachedThreadPool (); private static final ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator (executorService); / * callback method Mapping * / private static ConcurrentHashMap callbackMap / * storing key-value pairs, adding expiration time, and consumption callback * * @ param key * @ param timeout * @ param consumer * / public static void put (String key, String value, Long timeout, Consumer consumer) {TIMED_CACHE.put (key, value, timeout); addListen (key, consumer) } / * * get cache value * * @ param key * @ return * / public static String get (String key) {return TIMED_CACHE.get (key);} / * delete cache and callback mapping * * @ param key * / public static void remove (String key) {callbackMap.remove (key); TIMED_CACHE.remove (key) } / * add listeners * * @ param key * @ param consumer * / public static void addListen (String key, Consumer consumer) {ListenableFuture listenableFuture = listeningExecutorService.submit (()-> {while (TIMED_CACHE.containsKey (key)) {ThreadUtil.sleep (500);} return key ); Futures.addCallback (listenableFuture, new FutureCallback () {@ 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 ("", "1", 3000L, x-> System.out.println (MessageFormat.format ("[{0}]-cache vanished", x)); ThreadUtil.sleep (2000); System.out.println (get ("")); ThreadUtil.sleep (2000); System.out.println (get ("")); ThreadUtil.sleep (5000) System.out.println (get ("")); / / close the listening thread pool listeningExecutorService.shutdown ();}} these are all the contents of the article "how to use the TimedCache with time caching tool class in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report