运行几次弹簧测试时,Hibernate二级缓存已关闭

时间:2019-06-11 13:16:58

标签: spring hibernate ehcache

我正在尝试为基于Hibernate 5.3和Spring Boot 2.1.3并使用Hibernate二级缓存的应用程序编写测试。

当我执行一批测试时,这些测试正在设置spring上下文并尝试更新某些JPA实体,有时会出现如下异常:

org.springframework.dao.InvalidDataAccessApiUsageException: Cache[default-update-timestamps-region] is closed; nested exception is java.lang.IllegalStateException: Cache[default-update-timestamps-region] is closed

at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:370)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:536)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:533)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:304)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy244.save(Unknown Source)

我对Hibernate二级缓存具有以下配置:

spring.jpa.properties.hibernate.cache.use_second_level_cache=true spring.jpa.properties.hibernate.cache.use_query_cache=true spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE

并使用Hibernate JCache作为依赖项。

据我了解,org.hibernate.cache.jcache.JCacheRegionFactory对Spring Test创建的所有上下文重用EhCache CacheManager的相同实例,但是一段时间后Spring关闭缓存的上下文,这导致关闭CacheManager和缓存。

以前,Hibernate(Hibernate EhCache模块)提供了org.hibernate.cache.ehcache.EhCacheRegionFactory工厂,该工厂每次都在创建新的CacheManager,并且没有上述问题。

有人知道如何为每个Spring测试上下文创建新的CacheManager并避免使用共享的上下文吗?

2 个答案:

答案 0 :(得分:0)

此问题的一种可能的解决方法是将@DirtiesContext这样添加到您的班级:

@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class SomeTestClass {
...
}

这将迫使Spring为此类的所有方法创建一个新的应用程序上下文。就我而言,这解决了问题。

另一种方法是确保Spring知道Hibernate缓存管理器。可以像描述的in this blog post一样实现。但是,在某些情况下可能无法实现。

答案 1 :(得分:0)

GC的根本原因在于javax.cache.Caching,如果测试是在同一JVM中运行的,则其中CachingProvider的静态集合在所有Spring上下文之间共享。

在测试运行期间创建的Spring上下文共享相同的CachingProvider,因此也共享相同的CacheManagers。当共享CachingProvider的任何上下文关闭时,所有相关的CacheManager也都关闭,从而使剩余的Spring上下文引用关闭的CachingProvider处于不一致状态。

为解决此问题,每个对CacheManager的请求应返回一个不与其他上下文共享的全新实例。

我写了一个简单的CachingProvider实现,它依靠现有的CachingProviders来实现。请在下面找到代码。

基类:

import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.WeakHashMap;
import javax.cache.CacheManager;
import javax.cache.configuration.OptionalFeature;
import javax.cache.spi.CachingProvider;

/**
 * The abstract JCache compatible {@link CachingProvider} suitable for test purposes.
 *
 * <p>When using JCache and {@link org.hibernate.cache.jcache.JCacheRegionFactory}, {@link CachingProvider}-s
 * are shared between Spring contexts, which means that {@link CacheManager}-s are shared too. The class responsible
 * for storing loaded {@link CachingProvider}-s is {@link javax.cache.Caching}. If any cached Spring context is closed,
 * then all related {@link CacheManager}-s are closed as well, but since these {@link CacheManager}-s are shared with
 * remaining Spring contexts, we end up with in an inconsistent state.</p>
 *
 * <p>The solution is to make sure that each time a {@link CacheManager} for a particular config URI is requested, a new
 * instance not shared between Spring contexts is created</p>
 *
 * <p>The simplest approach is to create a new instance of {@link CachingProvider} for each {@link CacheManager} request
 * and manage them separately from {@link CachingProvider}-s loaded via {@link javax.cache.Caching}. This approach
 * allows reusing existing required {@link CachingProvider}-s and overcome any sharing issues.</p>
 *
 * <p>Tests relying on caching functionality MUST make sure that for regular caching the properties
 * {@code spring.cache.jcache.provider} and {@code spring.cache.jcache.config} are set and for 2nd-level cache
 * the properties {@code spring.jpa.properties.hibernate.javax.cache.provider} and
 * {@code spring.jpa.properties.hibernate.javax.cache.uri} are set. Please note that classpath URI-s for
 * the {@code spring.jpa.properties.hibernate.javax.cache.uri} property are supported by {@code hibernate-jcache} only
 * since 5.4.1, therefore with earlier versions this property should be set programmatically, for example via
 * {@link System#setProperty(String, String)}.</p>
 *
 * @see <a href="https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#caching-provider-jcache-cache-manager">Hibernate
 * JCache configuration</a>
 * @see org.hibernate.cache.jcache.JCacheRegionFactory
 * @see CachingProvider
 * @see javax.cache.Caching
 */
public abstract class AbstractTestJCacheCachingProvider implements CachingProvider {

    /**
     * The {@link CachingProvider}-s specific for a configuration {@link URI} for a specific {@link ClassLoader}.
     *
     * <p>All access MUST be handled in a <i>synchronized</i> manner.</p>
     */
    private final Map<ClassLoader, Map<URI, List<CachingProvider>>>
            classLoaderToUriToCachingProviders = new WeakHashMap<>();

    /**
     * {@inheritDoc}
     */
    @Override
    public CacheManager getCacheManager(URI uri, ClassLoader classLoader, Properties properties) {
        Objects.requireNonNull(uri, "The cache manager configuration URI must not be null.");
        Objects.requireNonNull(classLoader, "The class loader must not be null");

        final CachingProvider cachingProvider = createCachingProvider();
        synchronized (classLoaderToUriToCachingProviders) {
            classLoaderToUriToCachingProviders
                    .computeIfAbsent(classLoader, k -> new HashMap<>())
                    .computeIfAbsent(uri, k -> new ArrayList<>())
                    .add(cachingProvider);
        }
        return cachingProvider.getCacheManager(uri, classLoader, properties);
    }

    /**
     * Creates a {@link CachingProvider}.
     *
     * @return a created {@link CachingProvider}
     */
    protected abstract CachingProvider createCachingProvider();

    /**
     * {@inheritDoc}
     */
    @Override
    public ClassLoader getDefaultClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public URI getDefaultURI() {
        throw new UnsupportedOperationException("Please specify an explicit cache manager configuration URI.");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Properties getDefaultProperties() {
        return new Properties();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CacheManager getCacheManager(URI uri, ClassLoader classLoader) {
        return getCacheManager(uri, classLoader, null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CacheManager getCacheManager() {
        throw new UnsupportedOperationException("The cache manager configuration URI must be specified.");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void close() {
        synchronized (classLoaderToUriToCachingProviders) {
            classLoaderToUriToCachingProviders.keySet().forEach(this::close);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void close(ClassLoader classLoader) {
        Objects.requireNonNull(classLoader, "The class loader must not be null");

        synchronized (classLoaderToUriToCachingProviders) {
            // Process all CachingProvider collections regardless of the configuration URI.
            classLoaderToUriToCachingProviders
                    .getOrDefault(classLoader, Collections.emptyMap())
                    .values().stream().flatMap(Collection::stream)
                    // Close all CachingProvider resources since we are sure that CachingProvider-s are not shared
                    // or reused.
                    .forEach(CachingProvider::close);

            classLoaderToUriToCachingProviders.remove(classLoader);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void close(URI uri, ClassLoader classLoader) {
        Objects.requireNonNull(uri, "The cache manager configuration URI must not be null");
        Objects.requireNonNull(classLoader, "The class loader must not be null");

        synchronized (classLoaderToUriToCachingProviders) {
            final Map<URI, List<CachingProvider>> uriToCachingProviders = classLoaderToUriToCachingProviders
                    .getOrDefault(classLoader, Collections.emptyMap());
            uriToCachingProviders
                    .getOrDefault(uri, Collections.emptyList())
                    // Close all CachingProvider resources since we are sure that CachingProvider-s are not shared
                    // or reused.
                    .forEach(CachingProvider::close);

            uriToCachingProviders.remove(uri);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isSupported(OptionalFeature optionalFeature) {
        // Find the first available CachingProvider and delegate the request to it.
        synchronized (classLoaderToUriToCachingProviders) {
            return classLoaderToUriToCachingProviders.values().stream().findFirst()
                    .flatMap(uriToCachingProviders -> uriToCachingProviders.values().stream().findFirst())
                    .flatMap(cachingProviders -> cachingProviders.stream().findFirst())
                    .map(cachingProvider -> cachingProvider.isSupported(optionalFeature))
                    .orElse(false);
        }
    }
}

基于Ehcache的实现:

import javax.cache.spi.CachingProvider;
import org.ehcache.jsr107.EhcacheCachingProvider;

/**
 * The test {@link CachingProvider} based on {@link EhcacheCachingProvider}.
 */
public class TestEhcacheJCacheCachingProvider extends AbstractTestJCacheCachingProvider {

    @Override
    protected CachingProvider createCachingProvider() {
        return new EhcacheCachingProvider();
    }
}