Java C3P0:如何配置autoreconnect=true?

8

我正在使用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个回答

6
在类路径的根目录下创建一个名为c3p0.properties的文件:
# c3p0.properties
c3p0.testConnectionOnCheckout=true

如需进一步文档,请参阅此处

这篇文章也可能会有所帮助。


有人能解释一下什么是连接的签入和签出吗? - Kelly Beard

2

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

您可以在此处获取所有C3P0信息和示例:http://www.mchange.com/projects/c3p0/index.html

您可以使用外部属性文件或通过代码添加:例如如何使用数据源创建自定义池化数据源并添加自定义选项(更多示例请参见C3p0文档网址)

// 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 ); 

是的!好多了。MYSQL 官方已经强烈建议不要使用 autoreconnect - 它可能会导致数据损坏问题。抱歉,我没有链接 - 几年前看到的。 - MJB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接