60 lines of code write a simple and available memory cache with expiration time
It is very easy to use a cache in a small project. If you want to introduce other third-party caches such as Ehcache, you will need to add a variety of jars and even add configuration files. Special trouble.
So I wrote one for myself.
The idea is also very simple.
1, use a static decorated Concurrenthashmap object to save the data.
2, in the data stored in the actual data to add an external packaging, by the way plus deposit time, and expiration time.
3. Check whether the data is out of date, if expired, return directly null
4, the data can also add a data loader, if the cache has no data or has expired, then call the data loader to load the latest data and add the cache, and return.
The basic idea has the following to post the complete code.
Package com.data;
Import Java.util.Date;
Import Java.util.Map;
Import Java.util.concurrent.ConcurrentHashMap;
/** * Created by CYY on 2017/9/18. * * Public class CacheManager {private static map<string,cachedata> Cache_data = new Concurrenthashmap<> ()
;
public static <T> T getData (String key,load<t> load,int expire) {T data = GetData (key);
if (data = = NULL && load!= null) {data = Load.load ();
if (data!= null) {setData (key,data,expire);
} return data;
public static <T> T GetData (String key) {cachedata<t> data = Cache_data.get (key); if (Data!= null && (Data.getexpire () <= 0 | | | data.getsavetime () >= new Date (). GetTime ())) {Retur
n Data.getdata ();
return null; public static <T> void SetData (String key,t data,int expire) {Cache_data.put key,new (cachedataXpire));
public static void Clear (String key) {cache_data.remove (key);
public static void ClearAll () {cache_data.clear ();
public interface load<t>{T Load ();
private static Class cachedata<t>{CacheData (T t,int expire) {this.data = t; This.expire = expire <= 0?
0:expire * 1000;
This.savetime = new Date (). GetTime () + This.expire;
} private T data; Private long savetime; Survival time private long expire;
The expiration time is less than or equal to 0 identifies the permanently surviving public T GetData () {return data;
Public long Getexpire () {return expire;
Public long Getsavetime () {return savetime;
}
}
}
Use:
Package com.data;
Import Java.util.Map;
/**
* Created by the Administrator on 2017/9/18
. *
/public class Cachemanagertest {public
static void Main (String [] args) throws exception{
String key = "Test ";
String value = Cachemanager.getdata (key, New cachemanager.load<string> () {public
string Load () {return
" TestValue ";
}
},2);
System.out.println ("Value:" +value);
Thread.Sleep (3 * 1000);
String value2 = Cachemanager.getdata (Key, New cachemanager.load<string> () {
@Override public
string Load () {return
"what";
}
},3);
System.out.println ("value2:" + value2);
System.out.println ("Value3:" + cachemanager.getdata (key));
}