【发布时间】:2018-05-16 13:41:12
【问题描述】:
我正在尝试使用番石榴设置缓存,代码如下:
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 缓存?
【问题讨论】:
-
您的
Profile是否覆盖hashCode/equals? -
在核心对象中?是的。
-
我不明白这应该是如何工作的,你想从一些 other 配置文件中缓存一些配置文件 (
List)?您可能只想缓存活动配置文件吗? -
这正是我想要做的(缓存前 10 个活动配置文件)。但是,就像我说的那样,我真的不确定如何正确实施。
-
这样想——假设你想根据名字查询一些用户,所以你的缓存是
String, User,当String是notload方法/i> 在缓存中,稍后缓存;在第二次调用时,您的负载将不会被调用。所以基本上你只需做cache.get(String firstName)- 其余的将由缓存完成
标签: java spring caching guava dropwizard