Java DB 查询和 C3P0 用于并发调用

标签 java jdbc c3p0

我正在尝试了解 C3P0 和数据库调用。我最初有一个在 SQLite 上运行的程序,现在我尝试允许并发在 MariaDB 上测试查询。有几件事我没有掌握。 SQLite 的最初设计是有一个生产者线程将查询放入队列,还有一个消费者线程从队列中获取并向数据库发出数据库查询。

我想知道这个单个线程是否能够发出并发请求(因为它只是一个线程)。

其次,我遇到了一个问题,这个问题显然没有返回连接,或者看起来它在大约 18 个查询后停止了。队列中仍然有项目,但程序只是停止并等待尝试新连接。

我的主数据库调用线程类:

public class DBRunnable extends DBExtend implements Runnable
{
/**
 * Call the query builder instance
 */
protected QueryBuilder qb = QueryBuilder.getInstance();

/**
 * Call the point type converter instance
 */
protected PointTypeConv pv = PointTypeConv.getInstance();

/**
 * Singleton object
 */
private static DBRunnable db = null;

/**
 * Constructor
 */
public DBRunnable()
{
}

/**
 * Main thread functionality
 */
@Override
public void run()
{
    try
    {

        while (true)
        {

            long startTime = 0;

            QueryRequest msg = null;

            try
            {
                // Pull any existing query requests off the queue, if not, wait for one.
                msg = (QueryRequest) DBMigrationTool.dbProcQueue.take();
            } catch (Exception e)
            {
                errorLog.error("Unable to fetch message from message processing queue.");
            }

            // Good practice to create a new result set instead of reusing
            ResultSet rs = null;
            Statement stmt = null;

                    // Fetch the query and the request out of the QueryRequest object
                    String query = msg.getQuery();
                    // Make sure the query request isn't empty, if it is, there is no point in sending it to the DB

                    try (Connection conn = cpds.getConnection())
                    {
                        // Execute the given query and fetch the result from it
                        stmt = conn.createStatement();
                        startTime = System.currentTimeMillis();
                        stmt.setQueryTimeout(1800);
                        System.out.println(query);
                        stmt.execute(query);
                        rs = stmt.getResultSet();

                        if (rs != null)
                        {
                            try
                            {
                                int count = 0;
                                while (rs.next())
                                {
                                    count++;
                                }

                                System.out.println("Query Complete: " + (System.currentTimeMillis() - startTime) + "ms. Result count: " + count);

                                if (msg.getFlag() == 1)
                                {
                                    DBMigrationTool.flag = 0;
                                }

                            } catch (Exception e)
                            {
                                errorLog.error("Failed to process database result set.");
                            }

                        }
                        conn.close();
                    } catch (SQLException e)
                    {
                        errorLog.error("Query Error: " + msg.getQuery());
                        errorLog.error("Failed to issue database command: " + e);
                    } finally
                    {
                        if (rs != null)
                        {
                            try
                            {
                                rs.close();
                            } catch (SQLException e)
                            {
                                errorLog.error("Failed to close JDBC result set.");
                            }
                        }
                        if (stmt != null)
                        {
                            try
                            {
                                stmt.close();
                            } catch (SQLException e)
                            {
                                errorLog.error("Failed to close JDBC statement.");
                            }
                        }
                    }
                }                

    } finally
    {
        closeDB();
        DBMigrationTool.dbProcHandle.cancel(true);
    }

}

我的接口(interface)数据库类包含连接信息:

public class DBExtend
{
/**
 * Standard timeout
 */
public static final int DB_TIMEOUT = 30;

/**
 * Standard error logger for log4j2
 */
protected static Logger errorLog = LogManager.getLogger(DBExtend.class.getName());

/**
 * Call to the query builder instance
 */
private static QueryBuilder qb = QueryBuilder.getInstance();

/**
 * DB connection
 */
protected static ComboPooledDataSource cpds;

/**
 * Constructor
 */
public DBExtend()
{
}

/**
 * startDB is an initialization function used to open a database connection
 * 
 * @param dbPath - System path to the database file
 */
public void startDB(String dbPath)
{

    cpds = new ComboPooledDataSource();
    cpds.setJdbcUrl("jdbc:sqlite:" + dbPath);
    cpds.setMinPoolSize(1);
    cpds.setTestConnectionOnCheckout(true);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(20);

    errorLog.info("Connection to SQLite has been established.");

}

public void startMariaDB(String tableName)
{
    cpds = new ComboPooledDataSource();
    cpds.setJdbcUrl("jdbc:mariadb://localhost:3306/" + tableName);
    cpds.setUser("root");
    cpds.setPassword("joy");
    cpds.setMinPoolSize(1);
    cpds.setTestConnectionOnCheckout(true);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(20);

    errorLog.info("Connection to MariaDB has been established.");
}

/**
 * Close DB is to close a database instance
 */
public void closeDB()
{
    try
    {
        cpds.close();

        errorLog.info("Connection to SQLite has been closed.");

    } catch (SQLException e)
    {
        errorLog.error(e.getMessage());
    } finally
    {
        try
        {
            if (cpds.getConnection() != null)
            {
                cpds.getConnection().close();
            }
            if (cpds != null)
            {
                cpds.close();
            }
        } catch (SQLException ex)
        {
            errorLog.error(ex.getMessage());
        }
    }
}

}

最佳答案

JDBC 驱动程序必须是线程安全的,并且它抽象了实现细节。请注意,尽管驱动程序是线程安全的,但从多个线程同时使用同一个连接对象仍然不是一个好主意。

至于您的实际问题,您使用的 C3P0 数据源完全错误。连接池支持的数据源使用 getConnection() 方法为用户提供来自该池的连接。当您关闭该连接时,该连接将返回到池中。

这意味着您从池中获取连接,完成工作然后关闭它,以便将其返回到池中以供应用程序的其他部分使用。

这意味着DBRunnable中的以下代码是错误的:

if (cpds.getConnection().isValid(DB_TIMEOUT))

您从池中获取连接,然后立即泄漏它(它不会返回到池中),因为您没有引用它。请注意,大多数连接池(有时是可选的)在返回连接之前都会进行连接验证,因此没有必要对其进行测试。

与您的 DBExtend 类类似,这是错误的:

选择MariaDB中:

cpds.getConnection().setCatalog(DBName);

在这里,您从池中获取一个连接,并且永远不会关闭它,这意味着您已经“泄漏”了该连接。设置目录没有任何作用,因为该连接不会被重用。在这种情况下设置目录应该是连接池配置的一部分。

closeDB中:

cpds.getConnection().close();

这会从池中获取连接并立即关闭它(将其返回到池中)。这没有实际目的。

关于Java DB 查询和 C3P0 用于并发调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45922949/

相关文章:

java - C3p0 指定最大和最小空闲连接数

java - C3P0 一台服务器多个数据库

java - 将 Jersey 日志记录输出到文件?

java - autoCommit var 在关闭时是否在 c3p0 中重置?

java - JIRA升级需要下载哪个jar?

java - 如何在 JTable 中编辑行

postgresql - 使用 SSL 将 Pentaho Kettle/Spoon 连接到 Heroku PostgreSQL 时出现问题

java - Java 类中的 MySQL 语法错误?

java - 将 startForeground 与 android 服务一起使用

java - list.add(element) 不支持的操作异常