Guava - collections and Guava Cache

Guava - collections and Guava Caches

1. What is Guava

Guava is google launched a third-party java library for some public operation instead of the jdk, particularly impressed me is the extension and expansion of the local cache Collection of these two aspects. So today it is mainly to say something about two aspects of collection and guava caches.

2. dependence

Guava using very simple, can be introduced directly dependent maven:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>28.0-jre</version>
</dependency>

3. Collection collection

Guava provides us with a very useful set of tools api, reduce the complexity of native java code. Here a simple example here:

  1. Create a list:

    List<TypeThatsTooLongForItsOwnGood> list = Lists.newArrayList();
  2. Initialization list is also very simple:

    List<String> theseElements = Lists.newArrayList("alpha", "beta", "gamma");

    Comparison of Operating native java, java native operation becomes too cumbersome. (Create a list, then add elements into the list).

  3. There is also very simple to create a map:

    Map<KeyType, LongishValueType> map = Maps.newLinkedHashMap();

More detailed usage can refer to these two materials, here only do a brief introduction:

4. Caches

guava caches used when the local cache personally think is a very good choice.

1. Create a cache

for example:

​```java
private Cache<String, List<Integer>> localCache = CacheBuilder.newBuilder()
            .maximumSize(30)
            .expireAfterWrite(2, TimeUnit.MINUTES)
            .recordStats() 
            .build();
​```

Explanation of each parameter:

  • CacheBuilder.newBuilder () build ():. Creating a Cache cache object.
  • maximumSize (30): 30 to set the maximum storage objects. When an object is stored over 30, key-value of the least recently used will be recycled (LRU algorithm) [based on the size of the memory footprint recovered]
  • exprieAfterWrite (2, TimeUnit.MINUTES): set the expiration time to add the Cache represents object expires after 2 mins. [Time-based recovery]
  • recordStats (): open switch statistics
2. Query or save data

Use get method the data stored in the local cache or query data.

Cache get method has two parameters, the first parameter is acquired from the Cache recording key, a second record is Callable object. When the cache key corresponding to the record already exists, get method returns the corresponding key record. If the cache does not contain the corresponding record key, Guava starts a thread executes a method call Callable object, call the return value will be stored as a value corresponding to the cache key, and is returned to the get method.

for example:

localCache.get("key", () -> this.queryRedis(platformId, type))

He said it would redis to search out data into the local cache.

You can use getall()methods batch query

3. The cache invalidation

guava the method cache invalidation

  • invalidate(key): All waste values ​​value corresponding to the key currently in the cache.
  • invalidateAll(): All waste values ​​value cache.
  • invalidateAll(Iterable<?> keys): Incoming waste values ​​value set key corresponding to all the caches in.

for example:

localCache.invalidateAll() // 使所有缓存失效
4. Query status monitoring

Cache can hit rate, the time to load data for statistical and other information. When building Cache object, the switch can be turned by the statistics of CacheBuilder recordStats method. Cache automatically caches on various operating statistics after the switch is turned on, call the Cache stats ways to view information about the statistics.

localCache.stats();     // 获取统计信息

Several methods CacheStats in:

  • requestCount(): Returns the number of Cache lookup method to find the cache, regardless of the value lookup is cached.

  • hitCount(): Cache lookup method returns the number of cache hits.

  • hitRate(): Returns the cache hit rate request, the number of hits divided by the number of requests.

  • missCount(): Returns the number of cache misses request.

  • missRate(): Returns a cache miss ratio of a request, the request is divided by the number of misses.

  • loadCount(): Return the cached method call to load the new value of the number of loads.

  • loadSuccessCount(): Returns the number of successful cache loader new value.

  • loadExceptionCount(): Return the cached load the new value of the number of abnormal appearance.

  • loadExceptionRate(): Return the cached load the new value of the ratio abnormalities occur.

  • totalLoadTime(): Returns the total time to load a new value Cache consumed.

  • averageLoadPenalty(): Cache average time it takes to load a new value, divided by the total number of load time to load.

  • evictionCount(): Returns the number of entries in the cache are removed.

  • minus(CacheStats other): Returns a new instance of the difference between representation CacheStats CacheStats CacheStats current and incoming.

  • plus(CacheStats other): Returns a new instance of total representation CacheStats between CacheStats the current and incoming CacheStats.

Method 5. asMap

In any Cacheuse on asMapto ConcurrentMapview view cache.

Such as:

ConcurrentMap<String, List<Integer>> map = localCache.asMap(); 
6. More detailed usage:

5. guava official Chinese documents and documents

We can look at the official documentation wiki, very detailed. Both projects are hosted on GitHub.

Guess you like

Origin www.cnblogs.com/weixuqin/p/11374744.html