java - 使用 CompletableFuture 和缓存进行处理
问题描述
在一些帮助下,我能够使用 Completable futures 进行异步编程。但是,在应用程序的开头,我正在创建一个缓存,代码如下:
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.*;
import org.h2.table.Plan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class test {
private static final Logger LOGGER = LoggerFactory.getLogger(test.class);
private static LoadingCache<String, Plan> something;
public static void initLoadingCache( ) {
if (something == null) {
something = CacheBuilder.newBuilder()
.concurrencyLevel(10)
.maximumSize(1000) // Maximum of 1000 records can be cached
.expireAfterWrite(60, TimeUnit.MINUTES) // Cache will expire after 60 minutes
.build(new CacheLoader<String, Plan>() { // Build the CacheLoader
@Override
public Plan load(String key) throws Exception{
Plan record = getGraphFromDB(key);
if (record == null) LOGGER.error("DB {} is not present", record);
return record;
}
});
}
}
}
getGraphFromDB
除了运行正确的 SQL 查询之外什么都不做。我在日志中观察到我得到record
的null
结果,因此我抛出了异常。经过进一步调查,我发现我得到No session currently bound to execution context
了错误。我@UnitOfWork
在方法的开头添加了使用 Completable Future 执行异步处理的方法(如何在 CompletableFuture 任务上执行转换)。问题仍然存在,我无法找出它发生的原因。
根据评论更新:
public Plan getGraphFromDB(String key) throws Exception{
Session session = sessionFactory.openSession();
try {
ManagedSessionContext.bind(session);
Transaction transaction = session.beginTransaction();
try {
return somequery(key);
transaction.commit();
}
catch (Exception e) {
transaction.rollback();
throw new Exception(e.getMessage());
}
} finally {
session.close();
ManagedSessionContext.unbind(sessionFactory);
}
}