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