gpt4 book ai didi

java - 野蝇 11/Java EE 7/JSR 107 : caching - what's the best way to cache information and let it expire automatically?

转载 作者:行者123 更新时间:2023-11-29 08:32:35 25 4
gpt4 key购买 nike

在 Java EE/WebApp 容器中存储数据片段并让它自动过期的推荐方法是什么?我可以使用 session 持久性机制,但我的 http session 通常比我希望保留这些信息的时间长很多。

Java EE 7 或 CDI 是否提供了一些东西? JCache 规范 JSR 107 的一些初步变体?还有其他好的解决方案吗?

最佳答案

我不确定这是“最佳”方式,但我一直在使用 Google Guava cache在 Wildfly 中(8 到 10,但希望仍然适用)。对我来说,由于身份验证服务器非常慢,我正在缓存 Oauth token 。我的代码看起来像:

private static LoadingCache<String, MyPrincipal> tokenCacheMap;

@PostConstruct
private void postConstruct() {
tokenCacheMap = CacheBuilder.newBuilder()
.expireAfterAccess(15, TimeUnit.MINUTES)
.build(
new CacheLoader<String, MyUserPrincipal>() {
@Override
public MyUserPrincipal load(String token) {
MyUserPrincipal myUserPrincipal = getUserFromToken(token);

if( myUserPrincipal != null ) {
myUserPrincipal.setToken(token);
return myUserPrincipal;
}

throw new SecurityException("token is not valid");
}
}
);
}

//
// later in the code...
//
MyUserPrincipal myUserPrincipal = tokenCacheMap.get(token);

基本上,它所做的是设置一个缓存,让 token 在其中保存 15 分钟。如果需要,将调用 load() 方法以获取身份验证 token 和用户。缓 stub 据需要延迟填充 - 第一次调用将产生获取 token 的开销,但之后它全部在内存中。

还有其他选项,例如,根据缓存中的项目数驱逐旧信息。文档非常好,应该可以帮助您继续前进。

缺点是这不是 JEE 标准,但过去对我有用。

关于java - 野蝇 11/Java EE 7/JSR 107 : caching - what's the best way to cache information and let it expire automatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46750063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com