使用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查询外什么也不做。 我在日志中发现recordnull,因此抛出了异常。经过进一步调查,我发现我得到No session currently bound to execution context 作为错误。我在方法的开头添加@UnitOfWork,在其中使用Completable Future(How to perform the transformation on CompletableFuture tasks)执行异步处理。问题仍然存在,我无法找出原因。

根据评论进行更新:

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);
        }
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)