【问题标题】:Java boiler plate code: connection managementJava样板代码:连接管理
【发布时间】:2012-07-21 05:30:18
【问题描述】:

我们在处理连接池时通常有以下代码:

connection c = pool.borrow();
try {
    business-logic-using-connection(c);
}
catch(connectionException e) {
    connectionBad = true;
} 
finally{
    if (connectionBad) {
        pool.evict(c);
    } else {
       pool.return(c);
    }
 }

问题是如何使这个样板代码更简单,以便可以执行以下操作:

getConnectionAndDoWork(pool, business-logic-code)

可以插入他们的业务逻辑,而不必到处重复相同的连接管理代码。一种方法是为业务逻辑代码创建一个接口,例如doWorkWithConnection,它需要一个连接并做一些工作。但是,这限制了应该返回的业务逻辑代码;

有没有更好的方法在 Java 中做到这一点?

【问题讨论】:

    标签: java connection-pooling meta


    【解决方案1】:

    使用 Spring 对programmatic transaction management 使用的回调模式。

    interface PooledConnectionCallback<T> {
      T doWithConnection(Connection c);
    }
    
    Pool pool = new Pool(poolParams);
    Integer returnedValue = pool.execute(
      new PooledConnectionCallback<Integer>() {
        public Integer doWithConnection(Connection c) {
          int someReturnValue = businessLogicUsingConnection(c);
          return someReturnValue;
        }});
    

    Pool#execute 方法中,您可以获得处理异常和清理所需的样板代码。

    【讨论】:

    • 什么是 pool#execute 签名?
    • &lt;T&gt; T Pool#execute(PooledConnectionCallback&lt;T&gt;)
    【解决方案2】:

    如果您使用的是 Spring,请考虑使用 JdbcTemplate 或 NamedParameterJdbcTemplate:

    http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html

    http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html

    即使您不使用 Spring,您仍然可以使用相同的基本模板方法模式。只是谷歌“模板方法”。有很多关于它的文章。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多