最新在项目中发现一个LoadingCache类。是Google提供的一种本地缓存。挺好使的。分享一下。
Maven:
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.6.0</version>
</dependency>
Demo:
@Service
public class UserInfoSeviceImpl implements UserInfoService {
private static final String DEPARTMENT_CACHE_KEY = "all-department-info";
@Autowired
private DepartmentDao departmentDao;
/**
* 本地缓存
*/
private LoadingCache<String, List<DepartmentEntity>> loadingCache = Caffeine.newBuilder().maximumSize(10)
.refreshAfterWrite(5, TimeUnit.MINUTES).build(key -> departmentDao.queryDepartmentAll());
public List<DepartmentEntity> getDepartmentAll() {
return loadingCache.get(DEPARTMENT_CACHE_KEY);
}
}
使用起来非常简单方便。两行代码。