Java本地缓存简单使用例子

Java本地缓存简单使用例子

Java本地缓存简单使用例子

本文简单举例java本地缓存Cache的使用

1、实体类

import java.io.Serializable;
import lombok.Data;

/**
 * 功能描述:实体类
 *
 * @author yang.kuowei
 * @version 1.0
 * @date 2020/01/01 16:22
 */
@Data
public class Person implements Serializable {
    private String userName;

    private String address;

    private String userId;

}

2、缓存类

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;

/**
 * 功能描述:本地缓存demo
 *
 * @author yang.kuowei
 * @version 1.0
 * @date 2020/01/01 16:27
 */
public class PsersonCache {

    private static PsersonCache inst;

    private final Cache<String, Person> personCach = CacheBuilder.newBuilder().maximumSize(1000)
        .expireAfterWrite(30, TimeUnit.MINUTES).build();

    public void refreshLocalCahe() {
        personCach.invalidateAll();
    }

    /**
     * 根据健值获取缓存
     * @param key
     * @return
     */
    public Person getPerson(String key) {
        Person person = personCach.getIfPresent(key);
        if (person == null) {
            synchronized (this) {
                person = personCach.getIfPresent(key);
                if (person == null) {
                    person = getPersonFromDb(key);
                    if (person != null) {
                        personCach.put(key, person);
                    }
                }
            }
        }
        return person;
    }

    /**
     * 获取实例
     * @return
     */
    public static PsersonCache getInstance() {
        if (inst == null) {
            inst = new PsersonCache();
        }
        return inst;
    }

    /**
     * 根据健值刷新缓存
     */
    public void refreshCacheByKey(String key) {
        if (StringUtils.isNotEmpty(key)) {
            Person person = getPersonFromDb(key);
            personCach.put(key, person);
        }
    }

    /**
     * 使所有缓存失效
     */
    public void refresh() {
        refreshLocalCahe();
    }

    /**
     * 模拟从数据库获取数据
     *
     * @return Person
     */
    private Person getPersonFromDb(String userId) {
        Person person = new Person();
        person.setAddress("广西");
        person.setUserId("1001");
        person.setUserName("小明");
        return person;
    }
}

3、测试类

/**
 * 功能描述:测试类
 *
 * @author yang.kuowei
 * @version 1.0
 * @date 2020/01/01 19:10
 */
public class TestMain {
    public static void main(String[] args) {
        PsersonCache psersonCache = PsersonCache.getInstance();
        psersonCache.getPerson("1001");
        psersonCache.refresh();
        psersonCache.getPerson("1001");
        psersonCache.refreshCacheByKey("1001");
        psersonCache.getPerson("1001");
        psersonCache.getPerson("1001");
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值