When we use JDK local caches, we usually use HashMap or ConcurrentHashMap for local caches. Such as read-only data (loading dictionary table data), or independent data for each deployed node (in the long connection service, each deployed node maintains different connections, so data for each connection is independent). In the past, loading dictionary tables might have been done by loading all the dictionary table or configuration table information into the HashMap at boot time, and dealing with data expiration or validity issues yourself. If it’s not in the HashMap, the data is retrieved from the database, and the process of manually putting the data into the HashMap needs to be handled by the programmer. Using the Guava Cache, we can retrieve data from the database. The process of manually adding data to the HashMap does not need to be handled manually. We just need to define the logic to fetch data from the database. Here is a simple example of using properties as a data source instead of a database:
public class GuavaCache { private PropertiesUtil putil = new PropertiesUtil(); LoadingCache<String, String> cache = null; Private void init() {cache = cacheBuilder.newBuilder () // Cache maximum capacity.maximumSize(2) // If a cache item is not written (created or overwritten) within a specified period of time, it is reclaimed. This is desirable if you think that cached data always becomes stale and unusable after a fixed time. .expireAfterWrite(1, timeUnit.minutes) // Declare a listener, RemovalListener (new MyListener()).build(new CacheLoader<String, String>() { @Override public String load(String key) throws Exception { return putil.get(key); }}); } public static void main(String[] args) throws Exception { GuavaCache cache = new GuavaCache(); cache.init(); cache.testCache(); } private void testCache() { try { System.out.println("before:" + cache.size()); String name = cache.get("app.name"); cache.get("app.version"); cache.get("app.port"); System.out.println("after:" + cache.size()); System.out.println("name :" + name); } catch (Exception e) { e.printStackTrace(); } } private class MyListener implements RemovalListener<String, String> { @Override public void onRemoval(RemovalNotification<String, String> removalNotification) { String key = removalNotification.getKey(); String value = removalNotification.getValue(); RemovalCause cause = removalNotification.getCause(); System.out.println("key:"+ key + ",value:" + value + " removed, cause:" + cause.toString()); }}}Copy the code
The result is as follows:
before:0
key:app.name,value:MyApp removed, cause:SIZE
after:2
name :MyApp
Copy the code
In the Guava cache, every time a get is not present in the cache, it is loaded into the cache through the load method of the CacheLoader class we implemented. Because the maximum cache size is 2 (maximumSize), the RemovalListener will be called when data is removed.