[Google Guava]--cache tool

Introduction:

Guava provides a very powerful memory-based LoadingCache<K, V> through the interface LoadingCache. Automatically load values ​​in the cache, it provides many utility methods that are very useful when there is a need for caching.

interface declaration

The following is the declaration of the forcom.google.common.cache.LoadingCache<K,V> interface:

@Beta
@GwtCompatible
public interface LoadingCache<K,V>
   extends Cache<K,V>, Function<K,V>

interface method

S.N. Methods and Instructions
1 V apply(K key)
is deprecated. Provides a functional interface; use get(K) or getUnchecked(K) instead.
2 ConcurrentMap<K,V> asMap()
returns a view of the map entries stored in this cache as a thread-safe.
3 V get(K key)
returns a key in this cache, first loading the value associated with the value if needed.
4 ImmutableMap<K,V> getAll(Iterable<? extends K> keys)
returns a map of the values ​​associated with the keys, creating or retrieving these values ​​as necessary.
5 V getUnchecked(K key)
returns a key in this cache, first loading the value associated with the value if needed.
6 void refresh(K key)
loads the key key, possibly a new value asynchronously.

LoadingCache example

package com.koolearn.duobao.service;

import com.google.common.base.MoreObjects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author Franco_Q
 * @date 2018/3/23 17:26
 */
public class Test {
    public static void main(String args[]){
        //create a cache for employees based on their employee id
        LoadingCache employeeCache =
                CacheBuilder.newBuilder()
                        .maximumSize(100) // maximum 100 records can be cached
                        .expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access
                        .build(new CacheLoader<String, Employee>(){
                            @Override
                            public Employee load(String empId) throws Exception {
                                return getFromDatabase(empId);
                            } // build the cacheloader
                        });

        try {
            //on first invocation, cache will be populated with corresponding
            //employee record
            System.out.println("Invocation #1");
            System.out.println(employeeCache.get("100"));
            System.out.println(employeeCache.get("103"));
            System.out.println(employeeCache.get("110"));
            //second invocation, data will be returned from cache
            System.out.println("Invocation #2");
            System.out.println(employeeCache.get("100"));
            System.out.println(employeeCache.get("103"));
            System.out.println(employeeCache.get("110"));

        } catch (ExecutionException e) {
            e.printStackTrace ();
        }
    }

    private static Employee getFromDatabase(String empId){
        Employee e1 = new Employee("Mahesh", "Finance", "100");
        Employee e2 = new Employee("Rohan", "IT", "103");
        Employee e3 = new Employee("Sohan", "Admin", "110");

        Map database = new HashMap();
        database.put("100", e1);
        database.put("103", e2);
        database.put("110", e3);
        System.out.println("Database hit for" + empId);
        return (Employee) database.get(empId);
    }
}

class Employee {
    String name;
    String dept;
    String emplD;

    public Employee(String name, String dept, String empID){
        this.name = name;
        this.dept = dept;
        this.emplD = empID;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }
    public String getEmplD () {
        return emplD;
    }
    public void setEmplD(String emplD) {
        this.emplD = emplD;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(Employee.class)
                .add("Name", name)
                .add("Department", dept)
                .add("Emp Id", emplD).toString();
    }
}


Guess you like

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