Java MySQL 连接池不工作 [英] Java MySQL connetion pool is not working

查看:34
本文介绍了Java MySQL 连接池不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Java 编写了一个运行 MySQL 查询并返回结果的函数.我在这里使用这种方法实现了连接池:http://www.kodejava.org/how-do-i-create-a-database-connection-pool/.该函数正在工作,但连接时间仍然与没有池时相同~190 毫秒.有人能告诉我我做错了什么吗?

I've written a function in Java that runs a MySQL query and returns results. I've implemented connection pooling using this method here: http://www.kodejava.org/how-do-i-create-a-database-connection-pool/. The function is working, but connection time is still the same as it was without pooling ~190 ms. Can somebody tell me what am I doing wrong?

这是我的代码:

public static ArrayList<Map<String,Object>> query(String q) throws Exception {

    long start, end;

    GenericObjectPool connectionPool = null;

    String DRIVER = "com.mysql.jdbc.Driver"; 
    String URL = "jdbc:mysql://localhost/dbname";
    String USER = "root";
    String PASS = "";

    Class.forName(DRIVER).newInstance();

    connectionPool = new GenericObjectPool();
    connectionPool.setMaxActive(10);

    ConnectionFactory cf = new DriverManagerConnectionFactory(URL, USER, PASS);

    PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, connectionPool, null, null, false, true);

    DataSource ds = new PoolingDataSource(connectionPool);

    //create statement
    Statement Stm = null;

    try {

        Connection Con = null;
        PreparedStatement stmt = null;

        start = System.currentTimeMillis();

        Con = ds.getConnection();

        end = System.currentTimeMillis();
        System.out.println("DB Connection: " + Long.toString(end - start) + " ms");

        //fetch out rows
        ArrayList<Map<String, Object>> Rows = new ArrayList<Map<String,Object>>();

        Stm = Con.createStatement();

        //query
        ResultSet Result = null;

        boolean Returning_Rows = Stm.execute(q);

        if (Returning_Rows) {
            Result = Stm.getResultSet();
        } else {
            return new ArrayList<Map<String,Object>>();
        }

        //get metadata
        ResultSetMetaData Meta = null;
        Meta = Result.getMetaData();

        //get column names
        int Col_Count = Meta.getColumnCount();
        ArrayList<String> Cols = new ArrayList<String>();
        for (int Index=1; Index<=Col_Count; Index++) {
            Cols.add(Meta.getColumnName(Index));
        }

        while (Result.next()) {
            HashMap<String,Object> Row = new HashMap<String,Object>();
            for (String Col_Name:Cols) {
                Object Val = Result.getObject(Col_Name);
                Row.put(Col_Name,Val);
            }
            Rows.add(Row);
        }

        //close statement
        Stm.close();


        //pass back rows
        return Rows;

    } catch (Exception Ex) {

        System.out.print(Ex.getMessage());
        return new ArrayList<Map<String,Object>>();

    } finally {

        if (Stm != null) {
            Stm.close();
        }
        if (Stm != null) {
            Stm.close();
        }

        System.out.println("Max connections: " + connectionPool.getMaxActive());
        System.out.println("Active connections: " + connectionPool.getNumActive());
        System.out.println("Idle connections: " + connectionPool.getNumIdle());

    }

}

这是每次控制台输出:

DB Connection: 186 ms
Max connections: 10 
Active connections: 1 
Idle connections: 0 

更新: 我应该注意,使用它的 Java 应用程序是这样工作的:执行,只运行一个查询并关闭.我想如果 PHP 像这样工作并且它默认使用连接池,那么 Java 也应该这样吗?如果我错了,请纠正我.

UPDATE: I should note, that Java application that uses this works like this: executes, only runs one query and closes. I figured if PHP works like this and it's using connection pooling by default, so should Java? Correct me if I'm wrong.

推荐答案

您创建了一个连接池,但您没有将任何内容放入其中.您的连接池在创建时是空的,因此您对它的第一个请求肯定会创建一个新连接,并且与手动获取连接一样慢.

You create a connection pool, but you don't put anything into it. You connection pool is empty when it is created, so your first request to it is guaranteed to to create a new connection and will be just as slow as getting a connection manually.

尝试将您的代码放入一个循环中,在该循环中您反复从池中获得一个连接.尝试一次,五次,十次和十五次.请注意结果如何变化.

Try putting your code into a loop, where you repeatedly get a connection from the pool. Try it once, five times, ten times and fifteen times. Note how the results change.

某些连接池支持自动创建和保持最小数量的连接可供使用以及最大.当池初始化时,它将预取连接,因此前几次调用不会延迟.

Some connection pools support automatically creating and holding a minimum number of connections ready for use as well as a maximum. When the pool is initialised it will pre-fetch connections so the first few calls aren't delayed.

这篇关于Java MySQL 连接池不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆