Tomcat and JDBC connection pooling

后端 未结 2 466
情歌与酒
情歌与酒 2020-12-08 17:36

I am trying to set up connection pooling to mysql databe with tomcat. My simple app is called Projekt, in my Projekt.xml in Apache/conf/Catalina/localhost I have

<         


        
相关标签:
2条回答
  • 2020-12-08 17:44

    To achieve JDBC connection pooling with Tomcat, there is an alternative to the XML configuration files. I've never been able to get those Context and resource-ref tags to work. Furthermore those tags are overkill if you don't really need the JNDI features.

    The alternative is using Java code to configure Tomcat's JDBC connection pooling. See example code in the Plain Ol' Java section of Tomcat 7 documentation page, The Tomcat JDBC Connection Pool.

    Basically, you:

    1. Instantiate a PoolProperties object to store your settings (URL to database, db user name, db password, and such).
    2. Instantiate a Tomcat DataSource object while passing the PoolProperties object from step # 1 above.

    Easy peasy. Like this…

    PoolProperties p = new PoolProperties();
    p.setUrl( jdbc:postgresql://localhost:5432/" + "my_database_name" );
    p.setDriverClassName( "org.postgresql.Driver" );
    p.setUsername( "someUserName" );
    p.setPassword( "somePassword" );
    …
    DataSource datasource = new org.apache.tomcat.jdbc.pool.DataSource( p );
    datasource.setPoolProperties(p);
    

    To use the data source…

    Connection conn = null;
    try {
        conn = datasource.getConnection();
        …
    

    The DataSource instance can be stored:

    • As a member field on your Servlet.
    • As a Singleton as mentioned in another answer's comments.
    • As an “attribute” on the ServletContext using built-in mapping of String to Object, as described on an Answer of mine and as discussed on the Question How to get and set a global object in Java servlet context.
    0 讨论(0)
  • 2020-12-08 17:45

    Looks like you are missing Context envCtx = (Context) initCtx.lookup("java:comp/env");
    JNDI lookup should be done like this:

    // Obtain our environment naming context
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    
    // Look up our data source
    DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");
    
    // Allocate and use a connection from the pool
    Connection conn = ds.getConnection(); 
    

    documentation from http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html.

    0 讨论(0)
提交回复
热议问题