超时缓存 - TimedCache
# 超时缓存 - TimedCache
# 1. 介绍
TimedCache
是一种定时缓存,它允许我们为缓存的对象设置一个过期时间。对象在过期时间内会一直存在,当超过过期时间后,会被自动清理。这个缓存没有容量限制,对象只有在超时后才会被移除。
# 2. 使用方法
下面通过一个完整的代码示例来展示如何使用 TimedCache
:
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.thread.ThreadUtil;
public class TimedCacheExample {
public static void main(String[] args) {
// 创建一个 TimedCache 实例,默认过期时间为 4 毫秒
TimedCache<String, String> timedCache = CacheUtil.newTimedCache(4);
// 也可以通过实例化方式创建缓存,并指定默认过期时间
// TimedCache<String, String> timedCache = new TimedCache<>(4);
// 设置缓存项 key1,过期时间为 1 毫秒
timedCache.put("key1", "value1", 1);
// 设置缓存项 key2,过期时间为 5 秒
timedCache.put("key2", "value2", DateUnit.SECOND.getMillis() * 5);
// 设置缓存项 key3,使用默认过期时间(4 毫秒)
timedCache.put("key3", "value3");
// 启动定时任务,每 5 毫秒清理一次过期条目
// 如果不启动此定时任务,过期条目只会在调用 get 方法时被清理
timedCache.schedulePrune(5);
// 等待 5 毫秒,以便触发过期清理
ThreadUtil.sleep(5);
// 5 毫秒后,key1 和 key3 已过期,返回 null
String value1 = timedCache.get("key1"); // null
String value3 = timedCache.get("key3"); // null
// key2 由于过期时间为 5 秒,因此此时仍存在
String value2 = timedCache.get("key2"); // "value2"
// 如果想避免在调用 get 方法时重置过期时间,可以使用 get(key, false) 方法
String value2WithoutReset = timedCache.get("key2", false);
// 取消定时清理任务
timedCache.cancelPruneSchedule();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 代码解析
- 缓存创建与过期时间设置:在创建
TimedCache
时,我们可以指定默认的过期时间(例如 4 毫秒)。此外,在添加每个缓存项时,可以指定不同的过期时间。如果未指定,则使用默认过期时间。 - 定时任务与手动清理:通过
schedulePrune
方法启动一个定时任务,用于定期清理过期的缓存项。如果不启动此任务,缓存中的过期项只有在调用get
方法时才会被检查和清理。 - 缓存访问与超时重置:在默认情况下,调用
get(key)
方法时会重置该缓存项的过期时间。如果不希望重置,可以使用get(key, false)
方法。
# 使用场景
- 短生命周期数据:适用于缓存一些短时间内有效的数据,如临时配置、会话信息等。
- 避免内存泄漏:通过设置超时时间,可以防止长时间不使用的缓存占用内存资源,自动清理过期数据。
# 3. 关键方法与参数解析
put(String key, V value, long timeout)
:将数据放入缓存并设置过期时间。key
:缓存的键。value
:缓存的值。timeout
:过期时间,单位为毫秒。
get(String key)
:获取缓存中的数据,若缓存项过期则返回null
并清理。get(String key, boolean isReset)
:获取缓存中的数据,参数isReset
决定是否重置过期时间。isReset
为true
时,获取数据的同时重置过期时间。isReset
为false
时,不重置过期时间。
schedulePrune(long delay)
:启动定时清理任务,定期清理过期缓存项。cancelPruneSchedule()
:取消定时清理任务。
注意事项
- 定时任务的必要性:在需要及时清理缓存的场景中,建议启动定时任务,否则长时间不访问的缓存项不会被清理。
- 过期时间的重置:默认情况下,访问缓存时会重置过期时间,确保在频繁访问时缓存不会被移除。
编辑此页 (opens new window)
上次更新: 2024/12/28, 18:32:08