java c3p0:我如何配置autoreconnect = true?

时间:2010-08-18 11:12:08

标签: java mysql red5 c3p0

我正在使用Java编写一个red5应用程序 我正在使用c3p0进行数据库交互。

似乎在我的MySQL服务器中连接超时后,我的应用程序停止使用建议配置autoreconnect = true。

我该怎么办?

这是我用来创建数据源的函数:

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;
}

2 个答案:

答案 0 :(得分:6)

创建一个文件c3p0.properties,它必须位于类路径的根目录中:

# c3p0.properties
c3p0.testConnectionOnCheckout=true

有关进一步的文档,请参阅this

This post也可能有帮助。

答案 1 :(得分:2)

属性autoreconnect不是C3p0对象的一部分要使用C3P0池,建议配置其他选项(如 testConnectionOnCheckout ),以及使用Factory。

您在此处获得了所有C3p0信息和样本http://www.mchange.com/projects/c3p0/index.html

您可以使用和外部属性文件,或按代码添加:例如,如何使用数据源创建自定义池数据源并添加自定义选项(C3p0文档URL中的更多样本)

// Your datasource fetched from the properties file
DataSource ds_unpooled = DataSources.unpooledDataSource("url", "user", "password");


// Custom properties to add to the Source
// See http://www.mchange.com/projects/c3p0/index.html#configuration_properties                           

Map overrides = new HashMap();
overrides.put("maxStatements", "200");         //Stringified property values work
overrides.put("maxPoolSize", new Integer(50)); //"boxed primitives" also work

// Your pooled datasource with all new properties
ds_pooled = DataSources.pooledDataSource( ds_unpooled, overrides );