Search code examples
javamysqlred5c3p0

java c3p0: how can i configure autoreconnect=true?


I'm writing a red5 application using Java and I'm using the c3p0 for the database interaction.

It seems that after the connection as timed out in my MySQL server my application stops working with a suggestion to configure autoreconnect=true.

how can i do so?

this is the function that i use to create datasource:

private ComboPooledDataSource _createDataSource() {
    Properties props = new Properties();
    // Looks for the file 'database.properties' in {TOMCAT_HOME}\webapps\{RED5_HOME}\WEB-INF\
    try {
        FileInputStream in = new FileInputStream(System.getProperty("red5.config_root") + "/database.properties");
        props.load(in);
        in.close();
    } catch (IOException ex) {
        log.error("message: {}", ex.getMessage());
        log.error("stack trace: " + ExceptionUtils.getFullStackTrace(ex));
        return null;
    }

    // It will load the driver String from properties
    String drivers = props.getProperty("jdbc.drivers");
    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    try {
        cpds.setDriverClass(drivers);
    } catch (PropertyVetoException ex) {
        log.error("message: {}", ex.getMessage());
        log.error("stack trace: " + ExceptionUtils.getFullStackTrace(ex));
        return null;
    }

    cpds.setJdbcUrl(url);
    cpds.setUser(username);
    cpds.setPassword(password);
    cpds.setMaxStatements(180);

    return cpds;
}

Solution

  • Create a file c3p0.properties which must be in the root of the classpath:

    # c3p0.properties
    c3p0.testConnectionOnCheckout=true
    

    For further documentation refer to this.

    This post might be helpful also.