java - 如何在 Dropwizard 中实现番石榴缓存?
问题描述
我正在尝试使用番石榴设置缓存,代码如下:
private List<Profile> buildCache() {
LoadingCache cache = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(40)
.build(
new CacheLoader<Profile, List<Profile>>() {
@Override
public List<Profile> load(Profile profile) throws Exception {
Profile profile1 = new Profile();
Profile.setEmployed(true);
return profileDAO.getAllProfiles(Profile1, null);
}
}
);
return (List<Profile>) cache;
}
public List<Profile> getAllProfiles(Profile profile, Integer size) throws Exception {
return profileDAO.getAllProfiles(profile, size);
}
这里的想法是,这将使用获取所有配置文件创建缓存。该方法使用新的配置文件对象来设置该员工是否受雇的布尔值。size 变量意味着该方法将返回许多指示的值。为 null 时,默认为前 10。
我有两个问题: 1. 这是我第一次使用缓存,所以我真的不知道我是否正确执行此操作。2. 我在文档中找不到有关如何在我的应用程序中实现此功能的任何内容。我该怎么称呼这个?我尝试修改 getAllProfiles 方法以返回它:
public List<Profile> getAllProfiles(Profile profile, Integer size) throws Exception {
return buildCache();
}
但这只会返回一个我无法将缓存转换为 java 列表的异常:
Exception occurred: java.lang.ClassCastException: com.google.common.cache.LocalCache$LocalLoadingCache cannot be cast to java.util.List
如果有帮助的话,我的应用程序也在使用 spring,所以我也一直在研究它。springframework.cache.guava 和 google.common.cache 有什么区别,还是只是 Spring 内置的 guava 缓存?
解决方案
好的,我想我设法弄清楚了:
private LoadingCache<Integer, List<Profile>> loadingCache = CacheBuilder.newBuilder()
.refreshAfterWrite(10,TimeUnit.MINUTES)
.maximumSize(100).build(
new CacheLoader<Integer, List<Profile>>() {
@Override
public List<Profile> load(Integer integer) throws Exception {
Profile profile= new Profile();
if (integer == null) {
integer = 10;
}
return profileDAO.getAllProfiles(profile, integer);
}
}
);
首先,我应该指定传递给 LoadingCache 的键和值,在这种情况下,是一个整数和一个配置文件列表。此外,当我在构建函数中声明新的 CacheLoader 时,我应该保留键和值的布局。最后,当调用 getAll 方法时,我应该使用键 Integer 加载,而不是配置文件对象。
至于调用函数:
public List<Profile> getAllProfiles(Profile profile, Integer size) throws Exception {
return loadingCache.get(size);
}
这用于获取存储在缓存中的某些长度的列表。如果该长度的列表不在缓存中,则 getAll 方法将运行,使用您传递给它的大小变量。
@Eugene,感谢您的帮助。您对加载方法的解释确实帮助我了解了缓存。
推荐阅读
- javascript - 在循环中计算分数的总和
- python - 气流 - alembic.util.exc.CommandError:找不到由“a13f7613ad25”标识的修订版
- wpf - ScrollViewer (VerticalScrollBar) 中的垂直条不与用户控件一起显示,如 WPF XAML 中的扩展器
- qiskit - 没有名为“qiskit_metal”的模块
- java - Jave,报告不显示碧玉报告
- javascript - 使用 async-await 按特定顺序执行 javascript 函数
- javascript - javascript 未加载图像错误::ERR_FILE_NOT_FOUND
- php - 无法使用 onblur 函数发送多个表单变量
- r - 即使设置了语言环境,data.frames 中的藏文字符也无法在 R 控制台中显示(中文很好,矩阵中的藏文很好)
- python - 删除像素图 PyQt