【问题标题】:how to get static connection object in case of pooling?在池的情况下如何获取静态连接对象?
【发布时间】:2014-01-17 11:15:44
【问题描述】:

我无法理解如何在其他类中获得连接(我使用 DBCP 使用连接池)

MyServlet //不是完整的代码

 class MyServlet extends HttpServlet {

    public Datasource getDatasource(){

    Class.forName(driver).newInstance();

                ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectUri, username, password);

                PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, new GenericObjectPool(null), null, "SELECT null", false, true);

                connectionPool = new GenericObjectPool(poolableConnectionFactory);
                connectionPool.setMaxActive(10);
                connectionPool.setMaxIdle(4);

return new PoolingDataSource(connectionPool);

    }

现在我在 MyServlet 中有类似方法 getConnection 的东西

  public static Connection getConnection () {


    }

A) 如何在 getConnection() 静态方法中使用数据源?我不想将 getDatasource() 作为静态方法然后使用,因为当我们使用池机制时我觉得使用静态很危险

B) 请告诉我一种最终获得静态 getConnection() 并完美满足池化机制的方法..

【问题讨论】:

    标签: java apache jakarta-ee connection-pooling apache-commons-dbcp


    【解决方案1】:

    我建议使用Singleton 模式来获取连接可以达到目的。

    1) Make a private static final PoolingDataSource reference in your
    Servlet class
    
    2) Make your getDataSource() method static. Construct the
    PoolingDataSource instance when the PoolingDataSource reference in
    the Servlet class is null and return it to the calling method.
    Otherwise, just return the already initialized instance of
    PoolingDataSource
    
    3) Get the DataSource in the calling method and create new
    connections from it
    
    4) Close the Connection objects after use, in finally block
    

    【讨论】:

    • 在 getConnection() 静态方法中不能获取连接对象吗?
    • 是的,这是可能的。这就是我在回答中提到的。即这里调用方法是getConnection()
    • 我没明白你.. 我的主要问题是:我可以通过在 getCONnection() 的静态方法中执行 datasource.getConnection() 来获取连接对象,但是这样做让我做了'datasource' as static..请尝试理解我的问题..
    • 我可以知道您为什么要将数据源设为非静态的吗?您可以将 getDataSource 方法设为静态并获取数据源并创建连接
    • 那么,如果我将数据源变量保持为静态,连接池会有什么影响吗?有人告诉我,我们不应该在数据源的情况下使用静态
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    相关资源
    最近更新 更多