【发布时间】:2017-12-18 20:34:08
【问题描述】:
我想知道在 Stripes with Guice 中管理数据库连接的最佳实践。 理想情况下,我希望执行以下操作:
每个线程/http 请求使用一个 db 连接(可能使用 guice 将连接绑定到具有 ServletScope.REQUEST 范围的提供程序) 所有查询都在一个事务中执行,然后在最后提交或回滚。
我的问题是:什么应该创建/关闭我的数据库连接?
使用 Stripes 拦截器打开和关闭连接是不是一个坏主意?
我有一个管理器类的大型连接,它们都对我的数据库中的各种表执行自定义 SQL 查询。目前所有这些 Manager 类都有如下方法:
public abstract class MyManagerBase implements IMyManager {
@Inject
public void setConnection(Connection conn) {
this.conn = conn;
}
}
管理器自己子类化这个并且不创建或关闭连接。
我有这样的动作 bean:
public class MyActionBean implements ActionBean {
@Inject IMyManager myManager;
@DefaultHandler
public Resolution save() {
myManager.doStuff(...);
}
...
}
我有一个这样的 guice 配置:
public class MyConfigModule extends AbstractModule {
@Override
protected void configure() {
install(new ServletModule());
bind(IMyManager.class).to(MyManagerImpl.class);
bind(Connection.class).toProvider(MyConnectionProvider.class).in(ServletScopes.REQUEST);
}
到目前为止,我的想法是使用拦截器来注入管理器,同时为该 http 请求向所有管理器注入相同的连接。
到目前为止,我的拦截器尝试看起来像这样:
@Override
public Resolution intercept(ExecutionContext executionContext) throws Exception {
Connection conn = null;
switch( executionContext.getLifecycleStage() ) {
case ActionBeanResolution:
log.debug("Intercepting: ActionBeanResolution");
// Inject dependencies into ActionBeans
injector.injectMembers( executionContext.getActionBeanContext() );
Resolution resolution = executionContext.proceed();
injector.injectMembers( executionContext.getActionBean() );
return resolution;
case RequestComplete:
log.debug("Intercepting: RequestComplete");
executionContext.getActionBean();
Connection conn = injector.getInstance(Connection.class);
conn.commit();
conn.close();
}
}
}
【问题讨论】:
标签: java tomcat database-connection guice stripes