How to properly keep a DB connection from a Connection Pool opened in JBoss

后端 未结 2 1714
[愿得一人]
[愿得一人] 2020-12-21 19:03

I\'m using JBoss AS 7.1 as a server and I have my DataSource configured with pooling. I\'m quite new to this so please excuse any rookie mistakes... after all I\'m here to l

2条回答
  •  执念已碎
    2020-12-21 19:58

    How do I properly keep my connection opened?

    You must not do that, let the connection pool handle this.


    Behind the scenes, the connection pool will keep a bunch of database connections to the database engine (MySQL, Oracle, SQL Server... depends how you configure it) in SLEEPING state. When you execute this code:

    //avoiding all the particular exceptions just for code simplicity purposes...
    //in real world applications, you must handle each of these exceptions
    public Connection getConnection() throws Exception {
        ctx = new InitialContext();
        ds1 = (javax.sql.DataSource) ctx.lookup(strDSName1);
        return ds1.getConnection();
    }
    

    You're asking to the connection pool to retrieve one of these connections available. The connection pool will give you a database connection (if available) and let you use it as long as you want. Then you use it wherever you want/need and close it:

    public void foo() throws Exception {
        Connection connection = getConnection();
        //do what you want/need...
    
        //in the end, you close the connection
        //this is A MUST!
        connection.close();
    }
    

    When executing connection.close() from a connection retrieved by the connection pool, you're not closing the physical database connection but notifying the connection pool this specific database connection must return to the SLEEPING state.


    Some advices from the explanation:

    • You must not try to keep the connection alive, that's connection pool's job.
    • You must not try to store the connections in any cache-like structure, that's connection pool's job.
    • You must retrieve a java.sql.Connection in the shortest scope you will need it. Once you have used it, close it.

提交回复
热议问题