本地缓存(Guava Loading Cache)

线上环境部分请求的请求量十分巨大,将给缓存服务带来很大的压力,这时候为了提高服务整体性能,我们会考虑使用本地缓存,一方面能降低缓存服务的请求量,提高缓存服务性能,另一方面也能减少服务器与缓存服务之间的流量。当然使用缓存将带来数据一致性问题,所以使用本地缓存的场景需要仔细斟酌

Google的开源工具包Guava中提供了对本地缓存的实现,并且提供了类似Redis的缓存超时删除功能,简单易用

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

由于比较简单,这里直接贴代码了:

package com.sean;

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

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by seanzou on 2017/10/27.
 */
public class Cache {
    private static LoadingCache<Integer, People> cache = CacheBuilder
            .newBuilder()
            // 缓存容量
            .maximumSize(2)
            // 缓存超时时间
            .expireAfterWrite(5, TimeUnit.SECONDS)
            .build(new CacheLoader<Integer, People>() {
                // 缓存加载数据方式
                public People load(Integer id) throws Exception {
                    System.out.println("cache load " + id);
                    return new People(id,"people_"+id);
                }
            });

    public static void main(String[] args) throws Exception {
        System.out.println(cache.get(1));
        System.out.println(cache.get(2));
        // 由于缓存容量为2,因此会将key=1的数据从缓存移除,将key=3的数据插入缓存
        System.out.println(cache.get(3));
        System.out.println();

        List<Integer> keys = new LinkedList<Integer>();
        keys.add(1);
        keys.add(2);
        keys.add(3);
        // 查询所有缓存中的数据
        Map<Integer, People> map = cache.getAllPresent(keys);
        for(Integer key : map.keySet()){
            System.out.println(map.get(key));
        }
        System.out.println();

        TimeUnit.SECONDS.sleep(10);
        // 由于超时,缓存中的数据已被移除
        System.out.println(cache.getIfPresent(2));
        System.out.println(cache.getIfPresent(3));
        System.out.println();

        // 更新缓存的中数据
        cache.refresh(1);
    }
}

class People{
    private Integer id;
    private String name;

    public People(Integer id, String name){
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

运行结果如下:

cache load 1
People{id=1, name='people_1'}
cache load 2
People{id=2, name='people_2'}
cache load 3
People{id=3, name='people_3'}

People{id=2, name='people_2'}
People{id=3, name='people_3'}

null
null

cache load 1


猜你喜欢

转载自blog.csdn.net/a19881029/article/details/78415915