Javers SQL连接永远在使用中

时间:2016-02-01 16:07:55

标签: javers

我遇到的问题是数据库连接没有被发布'由javers。

我们使用Hibernate 5.0.6,Hikari作为我们的连接池,MSSQL Server作为我们的数据库。 Javers配置如下(片段):

JaversBuilder.javers().
    registerJaversRepository(SqlRepositoryBuilder.sqlRepository().
        withConnectionProvider(() -> ((SessionFactoryImpl) sessionFactory).getServiceRegistry().
            getService(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider.class).getConnection()).
        withDialect(DialectName.MSSQL).
        build()).
    build();

获取连接的方式很好。如果没有可用的连接池,则连接池将打开数据库连接。然而,由javers获得的连接是“使用”。永远。

61366 [Hikari Housekeeping Timer (pool HikariPool-0)] DEBUG HikariPool  - Before cleanup pool stats HikariPool-0 (total=100, inUse=100, avail=0, waiting=1)
61366 [Hikari Housekeeping Timer (pool HikariPool-0)] DEBUG HikariPool  - After cleanup pool stats HikariPool-0 (total=100, inUse=100, avail=0, waiting=1)
61366 [HikariCP connection filler (pool HikariPool-0)] DEBUG HikariPool  - After fill pool stats HikariPool-0 (total=100, inUse=100, avail=0, waiting=1)

我是否必须手动关闭连接?如果我尝试这个(只关闭我在一秒钟后给Javers的每个连接),连接池就会被清除。但是,这种方法不是一种选择。

有什么我想念的吗?如果我必须手动关闭连接,是否至少可以收到Javers的通知,它不再需要连接?

2 个答案:

答案 0 :(得分:0)

你不应该关闭连接,事实上你也不应该为JaVers打开新的连接。

主要想法是JaVers 重用连接和应用程序打开和关闭的事务。

示例场景:

  1. 应用程序从池中获取连接
  2. 应用程序执行一些DML操作,例如插入新人#1
  3. JaVers借用app的连接并插入Person#1的审核记录
  4. 应用程序提交(或回滚)事务并返回与池的连接
  5. 如果您使用的是JPA API,则可以使用与JaVers捆绑在一起的JpaHibernateConnectionProvider

    package org.javers.spring.jpa;
    ... //
    
    public class JpaHibernateConnectionProvider implements ConnectionProvider{
    
        @PersistenceContext
        private EntityManager entityManager;
    
        @Override
        public Connection getConnection() {
    
            SessionImpl session =  (SessionImpl)entityManager.unwrap(Session.class);
    
            return session.connection();
        }
    }
    

    如果你使用裸Hibernate,你可以编写类似的代码,它从当前的Hibernate会话(有界到当前线程)中提取连接。

答案 1 :(得分:0)

好的,这是我的解决方案。收集Javers获得的所有连接并关闭它们(close()不会关闭但是将它们释放到连接池!)在Javers完成工作之后:

收集连接的类:

public class ConnectionCleanup {

    private static final Logger LOG = LoggerFactory.getLogger(ConnectionCleanup.class);
    private static final ThreadLocal<List<Connection>> connections = new ThreadLocal<>();

    public static void add(final Connection connection) {
        List<Connection> listConnections = connections.get();
        if (listConnections == null) {
            listConnections = new ArrayList<>();
            connections.set(listConnections);
        }
        listConnections.add(connection);
    }

    public static void cleanup() {
        final List<Connection> listConnections = connections.get();
        if (listConnections == null) {
            return;
        }
        for (final Connection con : listConnections) {
            try {
                if (!con.isClosed()) {
                    con.close();
                }
            } catch (final Exception ex) {
                LOG.error("Caught an", ex);
            }
        }
        connections.set(null);
    }
}

在Javers工作完成后包装SqlRepository以调用cleanup:

public class CleanupJaversSqlRepository implements JaversRepository {

    private final JaversSqlRepository repository;

    public CleanupJaversSqlRepository(final JaversSqlRepository repository) {
        this.repository = repository;
    }

    @Override
    public Optional<CdoSnapshot> getLatest(final GlobalId globalId) {
        final Optional<CdoSnapshot> latest = repository.getLatest(globalId);
        ConnectionCleanup.cleanup();
        return latest;
    }

    @Override
    public void persist(final Commit commit) {
        repository.persist(commit);
        ConnectionCleanup.cleanup();
    }

    @Override
    public CommitId getHeadId() {
        final CommitId commitId = repository.getHeadId();
        ConnectionCleanup.cleanup();
        return commitId;
    }

    @Override
    public void setJsonConverter(final JsonConverter jsonConverter) {
        repository.setJsonConverter(jsonConverter);
        ConnectionCleanup.cleanup();
    }

    @Override
    public void ensureSchema() {
        repository.ensureSchema();
        ConnectionCleanup.cleanup();
    }

    @Override
    public List<CdoSnapshot> getStateHistory(
            final GlobalId globalId,
            final QueryParams queryParams) {
        final List<CdoSnapshot> stateHistory = repository.getStateHistory(globalId, queryParams);
        ConnectionCleanup.cleanup();
        return stateHistory;
    }

    @Override
    public List<CdoSnapshot> getPropertyStateHistory(
            final GlobalId globalId,
            final String propertyName,
            final QueryParams queryParams) {
        final List<CdoSnapshot> stateHistory = repository.getPropertyStateHistory(
                globalId, propertyName, queryParams);
        ConnectionCleanup.cleanup();
        return stateHistory;
    }

    @Override
    public List<CdoSnapshot> getStateHistory(
            final ManagedType givenClass,
            final QueryParams queryParams) {
        final List<CdoSnapshot> stateHistory = repository.getStateHistory(givenClass, queryParams);
        ConnectionCleanup.cleanup();
        return stateHistory;
    }

    @Override
    public List<CdoSnapshot> getPropertyStateHistory(
            final ManagedType givenClass,
            final String propertyName,
            final QueryParams queryParams) {
        final List<CdoSnapshot> stateHistory = repository.getPropertyStateHistory(
                givenClass, propertyName, queryParams);
        ConnectionCleanup.cleanup();
        return stateHistory;
    }

    @Override
    public List<CdoSnapshot> getValueObjectStateHistory(
            final EntityType ownerEntity,
            final String path,
            final QueryParams queryParams) {
        final List<CdoSnapshot> stateHistory = repository.getValueObjectStateHistory(
                ownerEntity, path, queryParams);
        ConnectionCleanup.cleanup();
        return stateHistory;
    }
}

最后,把它们放在一起:

JaversBuilder.javers().
                registerJaversRepository(new CleanupJaversSqlRepository(SqlRepositoryBuilder.sqlRepository().
                        withConnectionProvider(() -> {
                            final Connection connection = ((SessionFactoryImpl) sessionFactory).
                                    getServiceRegistry().getService(
                                            org.hibernate.engine.jdbc.connections.spi.ConnectionProvider.class).
                                    getConnection();
                            ConnectionCleanup.add(connection);
                            return connection;
                        }).
                        withDialect(DialectName.MSSQL).
                        build())).
                build();