In actual project development, we often use caching middleware (such as redis, MemCache, etc.) to help us improve the availability and robustness of the system.
But many times if the project is relatively simple, there is no need to specifically introduce middleware such as Redis to use cache to increase the complexity of the system. So does Java itself have any useful lightweight caching components?
The answer is of course yes, and there is more than one way. Common solutions include: ExpiringMap, LoadingCache and HashMap-based packaging.
Realize common functions of cache, such as outdated deletion strategy
Hot data warm-up
Entries in the Map can be set to automatically expire after a period of time.
You can set the maximum capacity value of the Map. When the Maximum size is reached, inserting a value again will cause the first value in the Map to expire.
You can add listening events and schedule the listening function when the Entry expires.
You can set up lazy loading and create objects when the get() method is called.
github address
Add dependency (Maven)
<dependency> <groupId>net.jodah</groupId> <artifactId>expiringmap</artifactId> <version>0.5.8</version> </dependency>
Example source code
public class ExpiringMapApp { public static void main(String[] args) { // maxSize: 设置最大值,添加第11个entry时,会导致第1个立马过期(即使没到过期时间) // expiration:设置每个key有效时间10s, 如果key不设置过期时间,key永久有效。 // variableExpiration: 允许更新过期时间值,如果不设置variableExpiration,不允许后面更改过期时间,一旦执行更改过期时间操作会抛异常UnsupportedOperationException // policy: // CREATED: 只在put和replace方法清零过期时间 // ACCESSED: 在CREATED策略基础上增加, 在还没过期时get方法清零过期时间。 // 清零过期时间也就是重置过期时间,重新计算过期时间. ExpiringMap<String, String> map = ExpiringMap.builder() .maxSize(10) .expiration(10, TimeUnit.SECONDS) .variableExpiration().expirationPolicy(ExpirationPolicy.CREATED).build(); map.put("token", "lkj2412lj1412412nmlkjl2n34l23n4"); map.put("name", "管理员", 20000, TimeUnit.SECONDS); // 模拟线程等待... try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("token ===> " + map.get("token")); System.out.println("name ===> " + map.get("name")); // 注意: 在创建map时,指定的那些参数如过期时间和过期策略都是全局的, 对map中添加的每一个entry都适用. // 在put一个entry键值对时可以对当前entry 单独设置 过期时间、过期策略,只对当前这个entry有效. } }
Run result
##token ===> nullAttentionname ===> Administrator
When creating a map, the specified parameters such as expiration time and expiration policy are global and apply to every entry added to the map.
When putting an entry key-value pair, you can set the expiration time and expiration policy separately for the current entry, which is only valid for the current entry.
public class LoadingCacheApp { public static void main(String[] args) throws Exception { // maximumSize: 缓存池大小,在缓存项接近该大小时, Guava开始回收旧的缓存项 // expireAfterAccess: 设置时间对象没有被读/写访问则对象从内存中删除(在另外的线程里面不定期维护) // removalListener: 移除监听器,缓存项被移除时会触发的钩子 // recordStats: 开启Guava Cache的统计功能 LoadingCache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterAccess(10, TimeUnit.SECONDS) .removalListener(new RemovalListener<String, String>() { @Override public void onRemoval(RemovalNotification<String, String> removalNotification) { System.out.println("过时删除的钩子触发了... key ===> " + removalNotification.getKey()); } }) .recordStats() .build(new CacheLoader<String, String>() { // 处理缓存键不存在缓存值时的处理逻辑 @Override public String load(String key) throws Exception { return "不存在的key"; } }); cache.put("name", "小明"); cache.put("pwd", "112345"); // 模拟线程等待... try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("token ===> " + cache.get("name")); System.out.println("name ===> " + cache.get("pwd")); } }
The outdated deletion hook triggered... key ===> name4.3 Removal mechanismWhen guava caches data, there are two types of data removal: passive removal and active removal. Passive removaltoken ===> Non-existent key
The obsolete deletion hook triggered... key ===> pwd
name ===> Non-existent key
The above is the detailed content of How to set expiration time map in Java. For more information, please follow other related articles on the PHP Chinese website!