[Google Guava]--缓存工具

简介:

Guava通过接口LoadingCache提供了一个非常强大的基于内存的LoadingCache<K,V>。在缓存中自动加载值,它提供了许多实用的方法,在有缓存需求时非常有用。

接口声明

以下是forcom.google.common.cache.LoadingCache<K,V>接口的声明:

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

接口方法

S.N. 方法及说明
1 V apply(K key)
不推荐使用。提供满足功能接口;使用get(K)或getUnchecked(K)代替。
2 ConcurrentMap<K,V> asMap()
返回存储在该缓存作为一个线程安全的映射条目的视图。
3 V get(K key)
返回一个键在这个高速缓存中,首先装载如果需要该值相关联的值。
4 ImmutableMap<K,V> getAll(Iterable<? extends K> keys)
返回一个键相关联的值的映射,创建或必要时检索这些值。
5 V getUnchecked(K key)
返回一个键在这个高速缓存中,首先装载如果需要该值相关联的值。
6 void refresh(K key)
加载键key,可能是异步的一个新值。

LoadingCache 示例

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();
    }
}


猜你喜欢

转载自blog.csdn.net/w372426096/article/details/79670421