Connections checking in c3p0 pool

前端 未结 3 2040
误落风尘
误落风尘 2021-02-10 07:41

I\'m developing with Java SE application using Hibernate 4 and c3p0 for communication with MariaDB database. It\'s long running application, waiting for signals from outside, so

3条回答
  •  清歌不尽
    2021-02-10 08:25

    Ok, i managed to fix all problems. Here is soultion.

    First of all, as Steve Waldman suggested, c3p0 wasn't actually initialized, but in Hibernate 4.3 hibernate.connection.provider_class parameter should be: org.hibernate.c3p0.internal.C3P0ConnectionProvider. In documentation you can read:

    A connection provider that uses a C3P0 connection pool. Hibernate will use this by default if the hibernate.c3p0.* properties are set.

    But in my opinion it's good to put this parameter by yourself, and it's needed if you are using c3p0 config file, not hibernate.c3p0.* properties.


    Second problem was obtaining session by calling SessionFactory.openSession() at the begining of the thread and later using always the same session object. I suppose after database connection was broken and there was new one recreated in pool, using old session caused using old, broken connection. So possible solutions were obtaining new session by SessionFactory.openSession() after catching connection error or using SessionFactory.getCurrentSession() at the begining of every communication. I've decided to use the second option (in this case my application waits for external signal, sometimes for hours, so I'm obtaining current session after each signal).


    My final configuration:

    hibernate.cfg.xml:

    
    
    
        
        org.hibernate.dialect.MySQLDialect
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/MyBase?zeroDateTimeBehavior=convertToNull&autoReconnect=true
        user
        pass
        org.hibernate.c3p0.internal.C3P0ConnectionProvider
    
        thread
    
        true
        true
    
        true
        true
        org.hibernate.cache.ehcache.EhCacheRegionFactory
        
    
    

    c3p0-config.xml:

    
    
        
        5
        5
        10
        3000
        30
    
        SELECT 1 FROM DUAL
        true
        false
        300 
        
    
    

    With this c3p0 configuration:

    • Every 5 minutes of not performing any queries on connection it will be tested, so it will never be invalidated by DB (in standard configuration MySQL invalidates connection after 8 hours of inactivity),
    • If DB will be restarted or connection(s) will be manually killed we have two options: a) after max 5 minutes connections will be reestablished, b) if application tries to perform query before automatic connection reestablishing HibernateException will be thrown, then connection will be reestablished and next query will succeed.

    Optionally testConnectionOnCheckout could be set to true to prevent exceptions, but it will cause performance troubles (see documentation).

提交回复
热议问题