我想知道使用 Guice 在 Stripes 中管理数据库连接的最佳实践。理想情况下,我想强制执行以下操作:
每个线程/http 请求使用一个 db 连接(可能使用 guice 将连接绑定到具有 ServletScope.REQUEST 范围的提供程序)所有查询都在一个事务中执行,然后在最后提交或回滚。
我的问题是:什么应该创建/关闭我的数据库连接?
使用 Stripes Interceptor 打开和关闭连接是不是一个坏主意?
我有大量的 Manager 类连接,它们都对我的数据库中的各种表执行自定义 SQL 查询。目前所有这些 Manager 类都有如下方法:
public abstract class MyManagerBase implements IMyManager {
@Inject
public void setConnection(Connection conn) {
this.conn = conn;
}
}
经理们自己继承这个,不创建或关闭连接。
我有这样的动作豆:
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();
}
}
}