Local Cache - Guava Cache of Application-Level Cache

refer to:

1.http://blog.csdn.net/kobejayandy/article/details/13277035

2.http://www.cnblogs.com/peida/p/Guava_Cache.html

 

1. Introduction to Guava:

1. The Google Guava library is a very good library that contains a lot of Java toolsets. Use Google Guava to write elegant code

 

2. Compared with the existing Apache Commons: The Google Guava library which is also excellent and is currently developing more rapidly than the Apache Commons series .

3. Content: Guava itself is the core Java basic library within Google, which covers collections, caches, basic types, concurrent processing, common annotations, string processing, I/O, networking, mathematical operations, reflection, range ( Range) and so on.

4. Why use Guava : Guava's active development and good quality assurance is one of the reasons why I prefer to switch to Guava. The various articles published by Guava over the years and its own good documentation style have also greatly helped the dissemination and use of the library.
Note: From the discussion on Stackoverflow above, the team led by Google's java development director is responsible for the library. The main maintenance work of the library


5. Guava related documents and resources are
recommended to visit Guava's knowledge base and API documentation. The
official website of Guava also gives the address of very useful learning resources:
Presentation slides focusing on base, primitives, and io
Presentation slides focusing on cache
Presentation slides focusing on util.concurrent
A nice collection of other helpful links

6. Using Guava
If you are using Maven as a project management and integration tool, just copy the following code into the project's pom.xml.
<dependency>
     <groupId>com.google.guava</groupId>
     <artifactId>guava</artifactId>
     <version>14.0-rc3</version>
</dependency>

 

 

二 .Guava cache

 

1. About caching

Cache: It is an indispensable 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 is to temporarily save the data processing results of the business system in memory, and wait for the next access to use. In many occasions of daily development, due to the limitation of the performance of hard disk IO or the data processing and acquisition of our own business system, it may be very time-consuming. When we find that our system has a large amount of data requests, frequent IO and frequent IO Logic processing can lead to bottlenecks in hard disk and CPU resources. The function of the cache is to store these difficult data in the memory. When other threads or clients need to query the same data resources, the data is directly returned from the cached memory block, which can not only improve the response time of the system, but also It can also save the resource consumption of the data processing process, and overall, the system performance will be greatly improved.

Cache is widely used in many systems and architectures, such as:
1. CPU cache 2. Operating system cache 3. Local cache 4. Distributed cache 5. HTTP cache 6. Database cache, etc.,
it can be said that in the computer and network Realm, caches are everywhere. It can be said that as long as there is asymmetric hardware performance, there will be caches where network transmission is involved.

 

2.Guava Cache

Guava Cache is a full-memory local cache implementation that provides a thread-safe implementation mechanism. Overall, Guava cache is the best choice for local caching, easy to use and good performance .

 

3. There are two ways to create Guava Cache

First: cacheLoader
Second: callable callback

These two methods are similar to the usual way of using map to cache
: both methods implement a logic - take the value of key-X from the cache, and if the value has already been cached, return it to the cache The value of , if it has not been cached, you can get this value through a method: the
difference:

The definition of cacheloader is relatively broad, and it is defined for the entire cache. It can be considered as a unified method of loadvalue according to the key value.

The callable method is more flexible, allowing you to specify when get

 

Implementation example of cacheLoader method

 

GuavaCacheUtil.java
@Test
    public void TestLoadingCache() throws Exception{
        LoadingCache<String,String> cahceBuilder=CacheBuilder
        .newBuilder()
        .build(new CacheLoader<String, String>(){
            @Override
            public String load(String key) throws Exception {       
                String strProValue="hello "+key+"!";               
                return strProValue;
            }
           
        });       
       
        System.out.println("jerry value:"+cahceBuilder.apply("jerry"));
        System.out.println("jerry value:"+cahceBuilder.get("jerry"));
        System.out.println("peida value:"+cahceBuilder.get("peida"));
        System.out.println("peida value:"+cahceBuilder.apply("peida"));
        System.out.println("lisa value:"+cahceBuilder.apply("lisa"));
        cahceBuilder.put("harry", "ssdded");
        System.out.println("harry value:"+cahceBuilder.get("harry"));
    }

 
  
output:
jerry value:hello jerry!
jerry value:hello jerry!
hide value: hello hide!
hide value: hello hide!
lisa value:hello lisa!
harry value:ssdded  
 
Implementation of callable callback:

 

 

GuavaCacheUtil.java
@Test
    public void testcallableCache()throws Exception{
        Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();
        String resultVal = cache.get("jerry", new Callable<String>() {
            public String call() {
                String strProValue="hello "+"jerry"+"!";               
                return strProValue;
            }
        });
        System.out.println("jerry value : " + resultVal);
       
        resultVal = cache.get("peida", new Callable<String>() {
            public String call() {
                String strProValue="hello "+"peida"+"!";               
                return strProValue;
            }
        });
        System.out.println("peida value : " + resultVal);
    }

 
output:
jerry value : hello jerry!
hide value: hello hide!
 
Cache parameter description :
  Recycling parameters:
  1. Size setting: 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. Explicit deletion: invalidate(key) invalidateAll(keys) invalidateAll()
  5. Remove listener: CacheBuilder.removalListener(RemovalListener)
  

  refresh mechanism:
  1. LoadingCache.refresh(K) When generating 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 refresh the cache


based on generic implementation:
/**
     * No need for delayed processing (generic way encapsulation)
     * @return
     */
    public  <K , V> LoadingCache<K , V> cached(CacheLoader<K , V> cacheLoader) {
          LoadingCache<K , V> cache = CacheBuilder
          .newBuilder()
          .maximumSize(2)
          .weakKeys()
          .softValues ​​()
          .refreshAfterWrite(120, TimeUnit.SECONDS)
          .expireAfterWrite(10, TimeUnit.MINUTES)       
          .removalListener(new RemovalListener<K, V>(){
            @Override
            public void onRemoval(RemovalNotification<K, V> rn) {
                System.out.println(rn.getKey()+"removed");
               
            }})
          .build (cacheLoader);
          return cache;
    }
   
    /**
     * Get value by key
     * Calling method commonCache.get(key) ; return String
     * @param key
     * @return
     * @throws Exception
     */
 
    public  LoadingCache<String , String> commonCache(final String key) throws Exception{
        LoadingCache<String , String> commonCache= cached(new CacheLoader<String , String>(){
                @Override
                public String load(String key) throws Exception {
                    return "hello "+key+"!";   
                }
          });
        return commonCache;
    }
   
    @Test
    public void testCache() throws Exception{
        LoadingCache<String , String> commonCache=commonCache("peida");
        System.out.println("peida:"+commonCache.get("peida"));
        commonCache.apply("harry");
        System.out.println("harry:"+commonCache.get("harry"));
        commonCache.apply("lisa");
        System.out.println("lisa:"+commonCache.get("lisa"));
    }
 
   
Generic-based Callable Cache implementation:
private static Cache<String, String> cacheFormCallable = null;

   
    /**
     * This mechanism can be used for those that require delayed processing; (generic packaging)
     * @param <K>
     * @param <V>
     * @param key
     * @param callable
     * @return V
     * @throws Exception
     */
    public static <K,V> Cache<K , V> callableCached() throws Exception {
          Cache<K, V> cache = CacheBuilder
          .newBuilder()
          .maximumSize(10000)
          .expireAfterWrite(10, TimeUnit.MINUTES)
          .build();
          return cache;
    }

   
    private String getCallableCache(final String userName) {
           try {
             //Callable will only be called if the cached value does not exist
             return cacheFormCallable.get(userName, new Callable<String>() {
                @Override
                public String call() throws Exception {
                    System.out.println(userName+" from db");
                    return "hello "+userName+"!";
               }
              });
           } catch (ExecutionException e) {
              e.printStackTrace ();
              return null;
            }
    }
   
    @Test
    public void testCallableCache() throws Exception{
         final String u1name = "peida";
         final String u2name = "jerry";
         final String u3name = "lisa";
         cacheFormCallable=callableCached();
         System.out.println("peida:"+getCallableCache(u1name));
         System.out.println("jerry:"+getCallableCache(u2name));
         System.out.println("lisa:"+getCallableCache(u3name));
         System.out.println("peida:"+getCallableCache(u1name));
        
    }
 
Description: Callable will be called only when the cached value does not exist, such as the second call to getCallableCache(u1name) to directly return the value in the cache

 

 


4. Guava Cache data removal

Passive removal and active removal

 

Three ways to passively remove data
1. Size-based removal

Understanding: From the literal meaning, you know that it is to be removed according to the size of the cache . If the specified size is about to be reached, it will remove the infrequently used key-value pairs from the cache.
Defined by:

Commonly used: CacheBuilder.maximumSize(long),

Not commonly used: There is also a method for calculating weights, which I personally think is not very useful in actual use.
As far as this common usage is concerned, there are several points to note:
(1) This size refers to the number of entries in the cache , not the memory size or other;
(2) The system does not start to remove infrequently when the specified size is reached. If the data is close to this size, the system will start to remove it ;
(3) If a key-value pair has been removed from the cache, when you request access again, if cachebuild uses cacheloader method, it will still take the value from the cacheloader again, if it has not, an exception will be thrown
  
2. Time-based removal

Understanding: guava provides two time-based removal methods

expireAfterAccess(long, TimeUnit)  

This method is based on how long after a key-value pair was last accessed

expireAfterWrite(long, TimeUnit)  

This method is based on how long it takes to remove a key-value pair after a key-value pair is created or a value is replaced.
  
3. Reference-based removal
understanding: This removal method is mainly based on the garbage collection mechanism of java, according to the reference relationship of keys or values. decided to remove
  

There are three ways to actively remove data:
1. Separate removal with Cache.invalidate(key)
2. Batch removal with Cache.invalidateAll(keys)
3. Remove all with Cache.invalidateAll()

 

If you need to take action when removing data, you can also define a Removal Listener, but it should be noted that the behavior in the default Removal Listener is executed synchronously with the removal action. If you need to change it to an asynchronous form, you can consider using RemovalListeners. Asynchronous(RemovalListener, Executor)


method comparison:
get(K): This method either returns the cached value, or uses the CacheLoader to atomically load the new value to the cache (that is, execute the Load method when the cache has no value)
put( key, value): This method can directly insert a value into the cache, which will directly overwrite the value mapped before the existing key.

Cache recycling :
CacheBuilder.maximumSize(long): This method specifies that the number of cache items does not exceed a fixed value (in fact, you can understand it as the maximum capacity of a Map), and try to recycle cache items that have not been used recently or are rarely used in general

. (Timed Eviction):
expireAfterAccess(long, TimeUnit): If the cache item has not been read/write accessed within a given time, it will be recycled. Note that the order of evictions for this cache is the same as for size-based evictions.
expireAfterWrite(long, TimeUnit): The cached item is reclaimed if it has not been write-accessed (created or overwritten) within the given time. This recycling method is desirable if it is considered that cached data will always become stale and unavailable after a fixed amount of time.














'

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326220523&siteId=291194637
Recommended