This is the 8th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
Author: Tom brother wechat public account: Micro technology
The local cache is typically located on the application server’s deployment machine and uses a small amount of memory from the application server itself. It is the first cache for the application layer to obtain data. When the application layer obtains data, it accesses the local cache first. If the data is not hit, it obtains the data from the L1 cache layer remotely.
Local caches are closer to the application and user devices and perform better than remote caches. Today, we’ll focus on a very popular native caching framework called Guava Caching
What is a Guava
Guava is an open source Java framework developed by Google. Provides features that the JDK does not provide, as well as enhancements to existing FEATURES in the JDK.
Include: Collections, Caching, Primitives Support, Concurrency Libraries, Common Annotations, and Strings Processing, Math, I/O, EventBus, etc.
Project integration
Import the corresponding binary package dependencies in the POM.xml file
<dependency> <groupId>com.google.guava</groupId> <artifactId> <version>23.0</version> </dependency>Copy the code
Initialize the local cache class instance and set various parameters to meet the requirements of personalized business scenarios.
Public class LocalCacheService {// LoadingCache Public static LoadingCache<Long, User> userCache = CacheBuilder.newBuilder() .concurrencyLevel(8) .expireAfterWrite(5, TimeUnit.SECONDS) .expireAfterAccess(20, TimeUnit.SECONDS) .refreshAfterWrite(3, TimeUnit.SECONDS) .initialCapacity(5) .maximumSize(10) .recordStats() .removalListener(new RemovalListener<Object, Object>() { @Override public void onRemoval(RemovalNotification<Object, Object> notification) {system.out.println (notification.getKey() + "removed, cause:" + notification.getcause ()); } }) .build( new CacheLoader<Long, User>() {@override public User load(Long ID) throws Exception {system.out.println (" @override public User load(Long ID) "+ id); return User.builder().id(id).userName("Lily").age(new Random().nextInt(20)).build(); }}); }Copy the code
Parameter description:
-
ExpireAfterWrite If the specified key is not created or overwritten within a certain period of time, the key will be removed. The key will be retrieved from loading next time
-
ExpireAfterAccess If no data is read or written on the specified key for a certain period of time, the key will be removed and the key will be retrieved from loading next time
-
RefreshAfterWrite Specifies that the key is not created/overwritten in a certain period of time, after the specified time, the next access, will refresh the cache, before the new value does not arrive, always return the old value
Key difference: after specified time, expire is removed, and the next access is synchronized to return the new value. In the case of refresh, the key will not be removed after the specified time. The next access will trigger refresh, and the old value will be returned before the new value is obtained
-
ConcurrencyLevel (8) sets the concurrencyLevel to 8. ConcurrencyLevel refers to the number of threads that can write to the cache at the same time
-
InitialCapacity the initialCapacity of the cache container is 5
-
MaximumSize (10) The maximum cache size is 10, after which the cache entries are removed according to LRU
-
RecordStats () measures the cache hit ratio. This is not required for online environments
-
RemovalListener (new removalListener <Object, Object>() sets the cache removal notification
-
Build () specifies a CacheLoader that automatically loads the cache if it does not exist
Construct a LoadingCache object that provides a number of methods to manipulate the cache, such asgetIfPresent
、put
,invalidate
For details, please refer to the following figure:
How to invalidate Guava cache:
-
Invalidate (key) : The value corresponding to the key in the cache is discarded.
-
InvalidateAll () : Deprecates all value values in the cache.
-
invalidateAll(Iterable<? > keys) : discards all caches of value values passed in to the key set.
CacheStats supports the following monitoring statistics dimensions:
-
RequestCount () : Returns the number of times the Cache lookup method has looked up the Cache, regardless of whether the value was cached.
-
HitCount () : Returns the number of times the Cache is hit by the Cache lookup method.
-
HitRate () : Returns the hit ratio of cached requests, the number of hits divided by the number of requests.
-
MissCount () : Returns the number of missed cache requests.
-
MissRate () : Returns the ratio of cache misses, the number of misses divided by the number of requests.
-
LoadCount () : returns the number of times the cache called the load method to load a new value.
-
LoadSuccessCount () : Returns the number of times the cache succeeded in loading a new value.
-
LoadExceptionCount () : Returns the number of times the cache failed to load a new value.
-
LoadExceptionRate () : Returns the rate at which the cache failed to load a new value.
-
TotalLoadTime () : returns the total time it took the cache to load the new value.
-
AverageLoadPenalty () : The average time the cache takes to load a new value, the total load time divided by the number of loads.
-
EvictionCount () : Returns the number of times an entry was removed from the cache.
-
Minus (CacheStats Other) : Returns a new CacheStats instance that represents the difference between the current CacheStats and the incoming CacheStats.
-
Plus (CacheStats Other) : Returns a new CacheStats instance representing the total between the current CacheStats and the incoming CacheStats.
The code address
https://github.com/aalansehaiyang/spring-boot-bulking modules: spring - the boot - bulking - guavaCopy the code
Author introduction: Tom brother, computer graduate student, recruited into Ali, P7 technology expert, patent, CSDN blog expert. In charge of e-commerce transactions, community fresh, traffic marketing, Internet finance and other businesses, many years of first-line team management experience