简体   繁体   中英

C3P0 connection pooling not working in spring mvc (maven project)

This is the applicationContext.xml file which i placed in the src/main/resources folder.

 <?xml version="1.0" encoding="UTF-8"?>

 <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"  xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


<context:property-placeholder location="classpath:jdbc.properties"/>

<!-- Employee DB data source. -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
    <property name="minPoolSize" value="${jdbc.minPoolSize}" />
    <property name="maxStatements" value="${jdbc.maxStatements}" />
    <property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
</bean>

<bean id="Utilities" class="com.pooling.test.Utilities">
</bean>

<context:component-scan base-package="com.pooling.controllers">
</context:component-scan>

This is the jdbc.properties file which i placed in the src/main/resources folder.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/books
jdbc.username=root
jdbc.password=admin
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=10
jdbc.testConnection=true
jdbc.unreturnedConnectionTimeout=240
jdbc.debugUnreturnedConnectionStackTraces=true

This is the Utilities class that contains the logic that i wish to perform

package com.pooling.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.jolbox.bonecp.BoneCP;

public class Utilities {

private final String CLASS_NAME = "Utilities";

@Autowired
private DataSource datasource;


 public String createListofCategories()
  {
    String METHOD_NAME = "createListofCategories()";


    /*//===========================================================================
     TransactionDefinition mDefinition = new DefaultTransactionDefinition();
     TransactionStatus mStatus = mTransactionManager.getTransaction(mDefinition);
     //===========================================================================  */

    String listOfCategories = "";

    String sequel = "select distinct category_id, key_desc from book_resource_view, keywords_record_table";

    sequel = sequel + " where keyword_key=category_id and category_id > 1 ";
    sequel = sequel + " order by key_desc";

    Connection connection = null;
    ResultSet results = null;
    Statement state = null;

    int categoryID = 0;
    String categoryDesc = "";
    int numRows = 0;
    try
    {

      connection = datasource.getConnection();
      state = connection.createStatement();
      results = state.executeQuery(sequel);
      results.last();
      numRows = results.getRow();
      //======================================
      results.beforeFirst();


      for(int i=0; results.next(); i++){
          listOfCategories = listOfCategories + "<td><ul id=\"category_list\">";

          for(int j=0; j<16; j++){

              categoryID = results.getInt("category_id");
              categoryDesc = results.getString("key_desc");

                listOfCategories = listOfCategories + "<li><a href=\"/DogearsETC2/dogears/categorytitles/"+categoryID+"/"+categoryDesc+"\">"+categoryDesc+"</a></li>";
              if(!results.next()){
                  break;
              }
          }
          results.previous();
          listOfCategories = listOfCategories + "</ul></td>";
      }

      listOfCategories = "<tr>"+listOfCategories+"</tr>";



    }
    catch (SQLException localSQLException)
    {

      try
      {
        results.close();
        state.close();
        connection.close();


      }
      catch (SQLException localSQLException1)
      {
      }


    }
    finally
    {
        try {
            results.close();
            state.close();
            connection.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }


    return listOfCategories;
  }

This is the controller code that i wish to call from the browser.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pooling.test.ConnectionManager;
import com.pooling.test.Utilities;


@Controller
public class TestController {


@RequestMapping(value="/testing",method=RequestMethod.GET)
public @ResponseBody String getCategories(){

    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Utilities utilities = (Utilities) context.getBean("Utilities");

    return utilities.createListofCategories();

}

}

PROBLEM: the problem is that the pool gets initialized properly but when i keep executing the same controller request again and again the connection pool keeps on creating connections until the server gives "too many connections" error

I think the problem lies in the fact that you create a new ApplicationContext everytime the getCategories() method is called.

As @Chrylis already mentioned, you don't need to call context.getBean().

Replace the two lines from ApplicationContext to context.getBean() to @Autowired Utilities utilities. Just like you did with datasource in your Utilities class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM