【问题标题】:Database connections not being closed with jpaFlowExecutionListener未使用 jpaFlowExecutionListener 关闭数据库连接
【发布时间】:2014-06-28 09:27:07
【问题描述】:

我正在使用 Spring Web Flow 来构建应用程序。我正在使用Flow Managed Persistence Context,因此实体管理器在我的流程执行期间“保持打开”,我可以访问延迟加载的属性(类似于OpenEntityManagerInViewFilterOpenSessionInViewFilter for Spring MVC)。我用这个的时候,每次提交表单,活跃的数据库连接数都会增加,如果我不使用FMPC,打开连接数没有问题。

我正在使用以下设置。

事务管理器

@Bean
@Autowired
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
}

数据源

@Bean
public DataSource dataSource() {
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty(PROPERTY_DATABASE_DRIVER));
    dataSource.setUrl(environment.getRequiredProperty(PROPERTY_DATABASE_URL));
    dataSource.setUsername(environment.getProperty(PROPERTY_DATABASE_USERNAME, ""));
    dataSource.setPassword(environment.getProperty(PROPERTY_DATABASE_PASSWORD, ""));
    return dataSource;
}

EntityManagerFactory

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    final LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setDataSource(dataSource());
    factoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_ENTITYMANAGER_PACKAGES_TO_SCAN));

    final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter() {
        {
            setDatabase(Database.valueOf(environment.getRequiredProperty(PROPERTY_DATABASE_TYPE)));
            setDatabasePlatform(environment.getRequiredProperty(PROPERTY_HIBERNATE_DIALECT));
        }
    };
    factoryBean.setJpaVendorAdapter(vendorAdapter);

    final Properties jpaProperties = new Properties();
    jpaProperties.put(PROPERTY_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_HIBERNATE_FORMAT_SQL));
    jpaProperties.put(PROPERTY_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_HIBERNATE_NAMING_STRATEGY));
    jpaProperties.put(PROPERTY_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_HIBERNATE_SHOW_SQL));
    jpaProperties.put(PROPERTY_HIBERNATE_HB2DDL_SQL, environment.getRequiredProperty(PROPERTY_HIBERNATE_HB2DDL_SQL));

    factoryBean.setJpaProperties(jpaProperties);

    return factoryBean;
}

JpaFlowExecutionListener

@Bean
@Autowired
public JpaFlowExecutionListener jpaFlowExecutionListener(EntityManagerFactory entityManagerFactory, JpaTransactionManager transactionManager) {
    return new JpaFlowExecutionListener(entityManagerFactory, transactionManager);
}

BasicDataSource 默认将maxActive 设置为 8,当我达到 8 个活动连接时,页面就会挂起。为什么请求完成后连接没有关闭?我已经使用 Chrome 调试工具(网络窗格)来确保没有 AJAX 请求正在运行或任何东西,我的页面提交(HTTP POST)触发了 301 重定向,然后给了我一个新的 HTTP GET 并导致状态200,一切都很好。

当从一个页面转到下一个页面时,会调用一个服务层,但正如您从我的 bean 中看到的那样,我使用的是 JpaTransactionManager,SWF 文档说明如下:

  • 注意:默认情况下,除了最终提交之外的所有数据访问都是非事务性的。但是,如果底层 JPA 事务管理器支持,流可以调用事务服务层以在对话期间在只读系统事务的上下文中获取对象。例如,在使用 Hibernate JPA 提供程序时,Spring 的 JPA TransactionManager 确实支持这一点。在这种情况下,Spring 将处理将 FlushMode 设置为 MANUAL 以确保不会刷新对托管持久实体的任何正在进行的更改,同时以事务方式读取新对象。

为了完整起见,我的 spring-web-flow 配置:

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:webflow="http://www.springframework.org/schema/webflow-config"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/webflow-config
           http://www.springframework.org/schema/webflow-config/spring-webflow-config.xsd">

    <!-- Flow executor, repsonsible for creating and executing flows -->
    <webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">
        <webflow:flow-execution-listeners>
            <webflow:listener ref="jpaFlowExecutionListener"/>
        </webflow:flow-execution-listeners>
    </webflow:flow-executor>

    <!-- Flow registry, responsible for loading all flows so executor can execute them -->
    <webflow:flow-registry id="flowRegistry" base-path="/WEB-INF/webflow/flows" flow-builder-services="flowBuilderServices">
        <webflow:flow-location-pattern value="/**/*-flow.xml"/>
    </webflow:flow-registry>

    <!-- Flow builder services -->
    <webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="mvcViewFactoryCreator"/>

    <!-- MvcViewFactoryCreator -->
    <bean id="mvcViewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
        <property name="viewResolvers">
            <list>
                <ref bean="viewResolver"/>
            </list>
        </property>
    </bean>

    <!-- Flow handler adapter, responsible for answering request for a flow -->
    <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
        <property name="flowExecutor" ref="flowExecutor"/>
    </bean>

    <!-- Flow handler mapping, lets Spring MVCs DispatcherServlet know to send flow request to SWF -->
    <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
        <property name="flowRegistry" ref="flowRegistry"/>
        <property name="order" value="0"/>
        <property name="interceptors">
            <list>
                <ref bean="localeChangeInterceptor" />
            </list>
        </property>
    </bean>
</beans>

我的流程在顶部定义了&lt;persistence-context /&gt;

我有以下结束状态(重新启动流程),即使我调用它并且 URL 参数更改为 e2s1,活动连接的数量也不会重置:

<end-state id="restart" commit="true" view="redirect:/main"/>

【问题讨论】:

    标签: spring spring-webflow


    【解决方案1】:

    所以hibernate.connection.release_mode 的默认休眠属性似乎是on_close。考虑到 EntityManager 在整个流程中保持打开状态,它永远不会关闭,并且会为流程中的每个请求从池中获取一个新连接。

    将属性更改为after_transaction 可解决此问题。但是,在获取延迟加载的集合的情况下,它仍然不起作用,每个延迟属性都会从池中获取一个新的连接。为了解决这个问题,我扩展了JpaFlowExecutionListener

    public class AvoidLeakJpaFlowExecutionListener extends JpaFlowExecutionListener {
    
        public AvoidLeakJpaFlowExecutionListener(EntityManagerFactory entityManagerFactory, PlatformTransactionManager transactionManager) {
            super(entityManagerFactory, transactionManager);
        }
    
        @Override
        public void paused(RequestContext context) {
            super.paused(context);
            EntityManager entityManager = (EntityManager) context.getFlowScope().get(PERSISTENCE_CONTEXT_ATTRIBUTE);
            if (entityManager != null && entityManager instanceof HibernateEntityManager) {
                HibernateEntityManager hibernateEntityManager = (HibernateEntityManager) entityManager;
                hibernateEntityManager.getSession().disconnect();
            }
        }
    }
    

    这种方法解决了延迟加载集合的问题,但仍然会泄漏连接当使用 WebFlow 的持久性上下文加载延迟初始化的实体并且在转换到未配置的子流期间执行此加载时。 em> 如in this bug report 中所述(我也在这里找到了这个解决方案)。

    【讨论】:

    • 我最近也遇到了这个问题,最终放弃了,并确保我需要为流程加载的所有内容都在流程启动时加载。
    猜你喜欢
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 2020-09-28
    • 2011-10-19
    相关资源
    最近更新 更多