What is Guava Cache?

Guava Cache is a very good local Cache solution provided by Google. It provides a thread-safe implementation mechanism and has the characteristics of easy to use and good performance. Guava Cache is not a separate Cache framework, but a module in Guava

Why do we use local caching?

  1. Faster and more efficient than centralized caches such as Redis

  2. To some extent, it can solve the big Key problem of Redis

Usage scenarios of Guava Cache

  1. Cache hotspot data locally and change space time to improve the anti-QPS capability of the service

  2. The cached data is limited and does not exceed the total memory limit

  3. Allow some delay in the data to achieve final consistency

Simple Demo

Next, we provide a Guava Cache build example:

private static LoadingCache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(20) .expireAfterWrite(10, TimeUnit.SECONDS) .refreshAfterWrite(5, TimeUnit.SECONDS) .build(new CacheLoader<String, String>() {@override public String Load (String key) throws Exception {log.info(" Data load, key: {}", key); return key + " : result"; }});Copy the code

Common Parameters

Guava Cache provides three Cache reclamation strategies:

  • Capacity reclamation: maximumSize

  • Scheduled reclamation: expireAfterAccess and expireAfterWrite

  • Reference recovery: softKeys, weakKeys

Introduction to core methods

load

The load method is triggered when the cache is loaded for the first time or there is no value corresponding to the key in memory (for example, the value has expired). For a key, multiple requests trigger only one load. For example, four threads obtain the value corresponding to the same key at the same time and the value does not exist. Then only one of the four threads will execute the load method, and the other requests will be hung. Therefore, when we use the local cache, we need to WarmUp in advance and load data into the local cache, otherwise it is easy to hang other requests.

reload

The reload method is triggered when the Cache contains a value that needs to be refreshed. All LoadingCache updates are triggered by read/write operations because there is no clock or scheduled task inside the Cache. For example, after a write operation, the refresh expiration time is exceeded. For the same Key, only one request triggers reload, and the other requests directly return the old value. The current GET thread is synchronous with the Call Reload method, and the other threads return the old value