Caching is an essential way to solve performance problems in our daily development. Simply put, cache is a piece of memory space opened up to improve system performance.
The main function of caching is to temporarily store the data processing results of the Business System in the memory and wait for the next access. In many daily development scenarios, it may take a long time to process and obtain hard disk I/O performance or the data of our business system, when we find that our system has a large amount of data requests, frequent IO and frequent logical processing will lead to bottlenecks in hard disks and CPU resources. The function of caching is to store the data from the hard nut to the memory. When other threads or clients need to query the same data resource, the data is directly returned from the cache memory block, this not only improves the system response time, but also saves the resource consumption of the data processing process. In general, the system performance will be greatly improved.
Caching is widely used in many systems and architectures, for example:
1. CPU Cache
2. operating system cache
3. Local Cache
4. distributed cache
5. HTTP Cache
6. database cache
In the computer and network fields, cache is everywhere. As long as the hardware performance is not correct, cache may appear in areas involving network transmission.
Guava Cache is a full-memory local Cache implementation that provides a thread-safe implementation mechanism. In general, Guava cache is the best choice for local cache, which is easy to use and has good performance.
Guava Cache can be created in two ways:
1. cacheLoader
2. callable callback
The cache created by using these two methods and the ratio of common map operations to cache are different in that, both methods implement a logic-Get the key X value from the cache. If the value has been cached, the value in the cache is returned. If the value has not been cached, you can use a method to obtain this value. However, the difference is that the definition of cacheloader is relatively broad, and it is defined for the entire cache. It can be considered as a unified method to load value based on the key value. The callable method is more flexible and allows you to specify it during get.
CacheLoader implementation example:
TestLoadingCache() <String,String> cahceBuilder= CacheLoader<String, String> String load(String key) ="hello "+key+"!""jerry value:"+cahceBuilder.apply("jerry""jerry value:"+cahceBuilder.get("jerry""peida value:"+cahceBuilder.get("peida""peida value:"+cahceBuilder.apply("peida""lisa value:"+cahceBuilder.apply("lisa""harry", "ssdded""harry value:"+cahceBuilder.get("harry"
Output:
jerry value:hello jerry!!!!!
Callable callback implementation:
testcallableCache()<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000= cache.get("jerry", Callable<String>="hello "+"jerry"+"!""jerry value : " += cache.get("peida", Callable<String>="hello "+"peida"+"!""peida value : " +!!
Cache parameters:
Recycling parameters:
1. Set the size: CacheBuilder. maximumSize (long) CacheBuilder. weigher (Weigher) CacheBuilder. maxumumWeigher (long)
2. Time: expireAfterAccess (long, TimeUnit) expireAfterWrite (long, TimeUnit)
3. Reference: CacheBuilder. weakKeys () CacheBuilder. weakValues () CacheBuilder. softValues ()
4. Clear deletion: invalidate (key) invalidateAll (keys) invalidateAll ()
5. Delete the listener: CacheBuilder. removalListener (RemovalListener)
Refresh mechanism:
1. When LoadingCache. refresh (K) is generated into a new value, the old value will still be used.
2. CacheLoader. reload (K, V) allows the use of the old value in the process of generating a new value
3. CacheBuilder. refreshAfterWrite (long, TimeUnit) automatically refreshes the cache
Implementation Based on Generics:
<K, V> LoadingCache <K, V> cached (CacheLoader <K, V> <K, V> cache = 212010 RemovalListener <K, V> onRemoval (RemovalNotification <K, v> + "removed" LoadingCache <String, String> commonCache (String key) <String, String> commonCache = cached (CacheLoader <String, String> String load (String key) "hello" + key + "! "TestCache () <String, String> commonCache = commonCache (" peida "" peida: "+ commonCache. get ("peida" "harry" "harry:" + commonCache. get ("harry" "lisa" "lisa:" + commonCache. get ("lisa"
Output:
peida:hello peida!!!
Implementation of generic Callable Cache:
Cache<String, String> cacheFormCallable = <K,V> Cache<K , V> callableCached() <K, V> cache =1000010 String getCallableCache( cacheFormCallable.get(userName, Callable<String> String call() +" from db" "hello "+userName+"!" testCallableCache() String u1name = "peida" String u2name = "jerry" String u3name = "lisa"="peida:"+"jerry:"+"lisa:"+"peida:"+
Output:
!!!!
Note: Callable is called only when the cache value does not exist. For example, the second call directly returns the value in the cache.
Guava Cache data removal:
When guava performs cache data removal, there are two types of data removal in guava: passive data removal and Active Data removal.
By default, guava provides three methods to remove data passively:
1. size-based removal: the removal is based on the cache size. If the specified size is reached, the infrequently used key-value pairs will be removed from the cache.
The definition method is generally CacheBuilder. maximumSize (long). There is also a method that can calculate the weight. I personally think it is not used in actual use. There are several points of attention in this common scenario,
First, this size refers to the number of entries in the cache, not the memory size or others;
Second, the system does not start to remove infrequently used data only when the specified size is reached. Instead, the system starts to remove the data when the size is approaching;
Third, if a key-value pair has been removed from the cache and you request access again, if cachebuild uses the cacheloader method, it will still retrieve the value from cacheloader again. If it does not exist, an exception will be thrown.
2. Time-based removal: guava provides two time-based removal methods.
ExpireAfterAccess (long, TimeUnit) is used to remove a key value after the last access.
ExpireAfterWrite (long, TimeUnit) This method is based on the time after a key-value pair is created or the value is replaced
3. Reference-based removal:
This removal method is mainly based on java's garbage collection mechanism. It is determined to be removed based on the reference relationship of the key or value.
There are three ways to actively remove data:
1. remove Cache. invalidate (key) separately)
2. Batch remove Cache. invalidateAll (keys)
3. Remove all Cache. invalidateAll ()
You can also define Removal Listener for some actions when removing data. However, you must note that the action in Removal Listener is executed synchronously by default. If you need to change it to asynchronous mode, you can consider using RemovalListeners. asynchronous (RemovalListener, Executor)