c3p0连接池中获取的Connection对象的close()方法是真的把连接给关闭了?

自己做写了一个管理数据源的DBManager,构想中从数据源里面获取的Connection使用完之后执行close()方法,然后把Connection对象闲置回连接池中。 但是测试出来的结果好像每次执行close()之后connection就销毁了。
代码如下:

DBManager.java

    package ben.DBUtils;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.log4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: Ben
 * Date: 13-7-3
 * Time: 下午5:06
 * To change this template use File | Settings | File Templates.
 */
public class DBManager {
    //保存数据库连接池的容器
    private static HashMap<String, ComboPooledDataSource> datasourceMap = new HashMap<String, ComboPooledDataSource>();
    private final static ThreadLocal<Connection> conns = new ThreadLocal<Connection>();
    private static Logger logger = Logger.getLogger(DBManager.class);

    static {
        InitDataSource(null);
    }


    /**
     * 初始化连接池
     * */
    private final static void InitDataSource(Properties dbProperties){
        try{
            if (dbProperties == null){
                dbProperties = new Properties();
                dbProperties.load(DBManager.class.getClassLoader().getResourceAsStream("dbInfo.properties"));
            }
            //获取数据源名称
            Set<String> keys = new HashSet<String>();
            for (Object key : dbProperties.keySet()){
                String skey = (String)key;
                Integer point = skey.indexOf(".");
                keys.add(skey.substring(0, point));
            }

            //实例化DataSource并放入容器中
            for (String key : keys)
            {
                ComboPooledDataSource ds = new ComboPooledDataSource();
                ds.setDriverClass(dbProperties.getProperty(key + "." + "Driver"));
                ds.setJdbcUrl(dbProperties.getProperty(key + "." + "Url"));
                ds.setUser(dbProperties.getProperty(key + "." + "User"));
                ds.setPassword(dbProperties.getProperty(key + "." + "Password"));
                ds.setMaxPoolSize(Integer.parseInt(dbProperties.getProperty(key + "." + "MaxPoolSize")));
                ds.setMinPoolSize(Integer.parseInt(dbProperties.getProperty(key + "." + "MinPoolSize")));
                ds.setMaxIdleTime(Integer.parseInt(dbProperties.getProperty(key + "." + "MaxIdleTime")));
                ds.setInitialPoolSize(Integer.parseInt(dbProperties.getProperty(key + "." + "InitialPoolSize")));
                ds.setAcquireIncrement(Integer.parseInt(dbProperties.getProperty(key + "." + "AcquireIncrement")));
                ds.setAcquireRetryAttempts(Integer.parseInt(dbProperties.getProperty(key + "." + "AcquireRetryAttempts")));
                ds.setAcquireRetryDelay(Integer.parseInt(dbProperties.getProperty(key + "." + "AcquireRetryDelay")));
                ds.setMaxStatements(Integer.parseInt(dbProperties.getProperty(key + "." + "MaxStatements")));
                ds.setIdleConnectionTestPeriod(Integer.parseInt(dbProperties.getProperty(key + "." + "IdleConnectionTestPeriod")));
                ds.setCheckoutTimeout(Integer.parseInt(dbProperties.getProperty(key + "." + "CheckoutTimeout")));
                ds.setTestConnectionOnCheckin(Boolean.parseBoolean(dbProperties.getProperty(key + "." + "TestConnectionOnCheckin")));
                ds.setTestConnectionOnCheckout(Boolean.parseBoolean(dbProperties.getProperty(key + "." + "TestConnectionOnCheckout")));

                datasourceMap.put(key, ds);

                Connection conn = getConnection(key);
                DatabaseMetaData metaData = conn.getMetaData();
                logger.info("Using DataSource: " + conn.getClass().getName());
                closeConnection();
            }

        }
        catch (Exception e){
            logger.error("DataSource Error:" + e.toString());
        }
    }

    /**
     * 断开连接池
     * */
    public  final static  void closeDataSource(String dataSourceName){
        try{
            ComboPooledDataSource dataSource = datasourceMap.get(dataSourceName);
            dataSource.close();
        }
        catch (Exception e){
            logger.error("Unable to destroy DataSource! " + e.toString());
        }
    }

    /**
     * 获取连接
     * @return Connection
     * */
    public final static Connection getConnection(String dataSourceName) throws SQLException{
        Connection conn = conns.get();
        if (conn == null || conn.isClosed()){
            ComboPooledDataSource dataSource = datasourceMap.get(dataSourceName);
            conn = dataSource.getConnection();
            conns.set(conn);
        }

        return conn;
    }

    /**
     * 关闭连接
     * */
    public final static void closeConnection(){
        Connection conn = conns.get();
        try{
            if (conn != null && !conn.isClosed()){
                conn.setAutoCommit(true);
                conn.close();
            }
        }
        catch (SQLException ex){
            logger.error("Unable to close connection! " + ex.toString());
        }
        finally {
            conns.remove();
            //conns.set(null);
        }
    }

}

dbInfo.properties

    DemoData.AcquireIncrement         = 2
DemoData.AcquireRetryAttempts     = 30
DemoData.AcquireRetryDelay        = 1000
DemoData.CheckoutTimeout          = 3000
DemoData.Driver                   = com.microsoft.sqlserver.jdbc.SQLServerDriver
DemoData.IdleConnectionTestPeriod = 18000
DemoData.InitialPoolSize          = 2
DemoData.MaxIdleTime              = 300
DemoData.MaxPoolSize              = 100
DemoData.MaxStatements            = 1000
DemoData.MinPoolSize              = 2
DemoData.Password                 = 123
DemoData.TestConnectionOnCheckin  = false
DemoData.TestConnectionOnCheckout = false
DemoData.Url                      = jdbc:sqlserver://localhost:1433;DatabaseName=DemoData
DemoData.User                     = sa

测试代码:TestDBManager.java

    package ben.DBUtils;

import java.sql.Connection;

/**
 * Created with IntelliJ IDEA.
 * User: Ben
 * Date: 13-7-6
 * Time: 上午12:28
 * To change this template use File | Settings | File Templates.
 */
public class TestDBManager {
    public static void main(String[] args) {
        for (Integer i=0; i<10; i++){
            try{
                System.out.println(DBManager.getConnection("DemoData"));
                DBManager.closeConnection();
                System.out.println("---------------------------");

            }
            catch (Exception ex){
                ex.printStackTrace();
            }
        }

    }
}

打印出来的结果每次都不一样

com.mchange.v2.c3p0.impl.NewProxyConnection@ff5c225

com.mchange.v2.c3p0.impl.NewProxyConnection@5bafcc2c

com.mchange.v2.c3p0.impl.NewProxyConnection@ded0b93

com.mchange.v2.c3p0.impl.NewProxyConnection@25057fe

com.mchange.v2.c3p0.impl.NewProxyConnection@198ad24a

com.mchange.v2.c3p0.impl.NewProxyConnection@1228bd68

com.mchange.v2.c3p0.impl.NewProxyConnection@36db09fa

com.mchange.v2.c3p0.impl.NewProxyConnection@35886ba1

com.mchange.v2.c3p0.impl.NewProxyConnection@17d8986

com.mchange.v2.c3p0.impl.NewProxyConnection@2bb9e538

1个回答

你的finally里面的 conns.remove(); 是干啥的?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
c3p0连接池 无需关注statement是否关闭吗
c3p0连接池 ,当connection.close()的时候,把数据连接还回连接池中,那么connection所产生的statement,resultset等对象是怎么关闭的?
c3p0连接池的无法获得连接对象,按照视频里添加里驱动程序仍然显示java.sql.SQLException: No suitable driver
![图片说明](https://img-ask.csdn.net/upload/201911/18/1574046716_109697.png) 我的服务器版本是8.0.12的,驱动jar包官网只能下在8.0.18的但是听说好像是向下兼容的 c3po的配置文件 ``` <?xml version="1.0" encoding="utf-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property> <property name="user">root</property> <property name="password">123456</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">10</property> <property name="checkoutTimeout">3000</property> </default-config> <named-config name="otherc3p0"> <property name="user">root</property> <property name="password">123456</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <!-- 如果池中数据连接不够时一次增长多少个 --> <property name="acquireIncrement">5</property> <!-- 初始化数据库连接池时连接的数量 --> <property name="initialPoolSize">20</property> <!-- 数据库连接池中的最大的数据库连接数 --> <property name="maxPoolSize">25</property> <!-- 数据库连接池中的最小的数据库连接数 --> <property name="minPoolSize">5</property> <property name="checkoutTimeout">3000</property> </named-config> </c3p0-config> ``` 主程序 ``` package cn.HSY; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; public class DataSoure01 { public static void main(String[] args) throws SQLException { DataSource dataSource=new ComboPooledDataSource(); Connection connection=dataSource.getConnection(); System.out.println(connection); } } ```
使用c3p0连接池是出现了空指针异常
连接不上我的mysql数据库,但是我单独测试又可以连接上,测试代码如下: Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/shi"; String name = "root"; String password = "root"; conn = DriverManager.getConnection(url, name, password); String sql = "select * from t_user"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while(rs.next()) { String username = rs.getString("name"); System.out.println(username); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if(rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } 但是使用c3p0的时候就出问题了: c3p0的配置如下: <?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/shi?useUnicode=true&amp;characterEncoding=utf8</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password">root</property> <!-- <property name="jdbcUrl">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="driverClass">oracle.jdbc.driver.OracleDriver</property> <property name="user">scott</property> <property name="password">tiger</property> --> <property name="c3p0.testConnectionOnCheckout">true</property> <property name="acquireIncrement">3</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">2</property> <property name="maxPoolSize">10</property> </default-config> </c3p0-config> 出现的异常如下: kate Tom 2014-8-9 9:31:05 com.mchange.v2.log.MLog 信息: MLog clients using java 1.4+ standard logging. 2014-8-9 9:31:06 com.mchange.v2.c3p0.C3P0Registry 信息: Initializing c3p0-0.9.5-pre8 [built 04-April-2014 04:20:15 -0700; debug? true; trace: 10] 2014-8-9 9:31:06 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource 信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 2sa1hd931f5tqer1kt6lht|2c766a24, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> null, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceUseNamedDriverClass -> false, identityToken -> 2sa1hd931f5tqer1kt6lht|2c766a24, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> null, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ] 2014-8-9 9:31:36 com.mchange.v2.resourcepool.BasicResourcePool 警告: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@6c3b78cf -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.lang.NullPointerException at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:507) at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:476) at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307) at java.sql.DriverManager.getDriver(DriverManager.java:253) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:278) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:158) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:161) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:147) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44) at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1814) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) 2014-8-9 9:31:36 com.mchange.v2.resourcepool.BasicResourcePool 警告: Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool@5c1fe88d is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests. 2014-8-9 9:31:36 com.mchange.v2.resourcepool.BasicResourcePool 警告: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@53416c84 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.lang.NullPointerException at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:507) at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:476) at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307) at java.sql.DriverManager.getDriver(DriverManager.java:253) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:278) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:158) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:161) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:147) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44) at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1814) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) java.sql.SQLException: Connections could not be acquired from the underlying database! at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:690) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140) at jdbcUtils.JdbcUtils.getConnection(JdbcUtils.java:44) at jdbcUtils.TestUtils.main(TestUtils.java:59) Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source. at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1422) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:756) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:683) ... 3 more 2014-8-9 9:31:36 com.mchange.v2.resourcepool.BasicResourcePool 警告: Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool@5c1fe88d is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests. 2014-8-9 9:31:36 com.mchange.v2.resourcepool.BasicResourcePool 警告: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@58a2353d -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.lang.NullPointerException at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:507) at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:476) at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307) at java.sql.DriverManager.getDriver(DriverManager.java:253) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:278) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:158) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:161) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:147) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44) at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1814) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) 2014-8-9 9:31:36 com.mchange.v2.resourcepool.BasicResourcePool 警告: Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool@5c1fe88d is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests.
Hibernate配置C3P0连接池报错
Hibernate+MySQL部署出现了java.net.SocketException: Broken pipe (Write failed)这个错误,查百度说是因为MySQL默认连接8小时的问题,所以想采用C3P0,附上Hibernate.xml配置如下: ``` <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="myeclipse.connection.profile">sces</property> <property name="connection.url"><![CDATA[jdbc:mysql://localhost:3306/sces?useUnicode=true&characterEncoding=UTF-8]]></property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.password">123456</property> <property name="connection.username">root</property> <!--c3p0设置--> <!--<property name="connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property>--> <!--<property name="hibernate.c3p0.min_size">5</property>--> <!--<property name="hibernate.c3p0.max_size">20</property>--> <!--<property name="hibernate.c3p0.max_statements">100</property>--> <!--<property name="hibernate.c3p0.timeout">3600</property>--> <!--<property name="hibernate.c3p0.idle_test_period">120</property>--> <!--<property name="hibernate.c3p0.acquire_increment">2</property>--> <mapping resource="entity/DCharacteristic.hbm.xml" /> <mapping resource="entity/DIops.hbm.xml" /> <mapping resource="entity/DPool.hbm.xml" /> <mapping resource="entity/DStatus.hbm.xml" /> <mapping resource="entity/Device.hbm.xml" /> <mapping resource="entity/User.hbm.xml" /> <mapping resource="entity/DDl.hbm.xml" /> <mapping resource="entity/Systeminfo.hbm.xml" /> <mapping resource="entity/DCapacity.hbm.xml"/> <mapping resource="entity/DErrlog.hbm.xml"/> <mapping resource="entity/DRack.hbm.xml"/> </session-factory> </hibernate-configuration> ``` 中间注释掉的为c3p0的部分,现在这种情况下能正常运行,但是打开c3p0后会报错: ``` 十二月 26, 2017 3:02:49 下午 com.mchange.v2.resourcepool.BasicResourcePool 警告: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@58f663e4 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.sql.SQLException: No suitable driver at java.sql.DriverManager.getDriver(DriverManager.java:278) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:285) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125) at com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44) at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) ``` 看起来是找不到驱动,但是明明不开连接池的时候能正常跑的,说明驱动没问题呀,为什么会这样呢 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 补充:直接在IDE中运行读取数据库的操作可以正常运行,但是把程序放到tomcat中就会 报这个错误,MySQL的驱动在tomcat的bin和lib中都放了,求解!!!!!
c3p0连接数据库一直出现Unable to acquire JDBC Connection
![图片说明](https://img-ask.csdn.net/upload/201912/24/1577183334_328248.png)![图片说明](https://img-ask.csdn.net/upload/201912/24/1577183463_24927.png) **一按登录就出现500,说jdbc连接失败,求求大佬** Type Exception Report Message JDBC exception on Hibernate data access: SQLException for SQL [n/a]; SQL state [null]; error code [0]; Unable to acquire JDBC Connection; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection Description The server encountered an unexpected condition that prevented it from fulfilling the request. Exception org.springframework.orm.hibernate5.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [n/a]; SQL state [null]; error code [0]; Unable to acquire JDBC Connection; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:254) org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:388) org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:347) org.springframework.orm.hibernate5.HibernateTemplate.find(HibernateTemplate.java:831) com.dao.impl.UserDaoImpl.findByName(UserDaoImpl.java:43) com.struts.action.LoginServiceAction.execute(LoginServiceAction.java:45) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:873) ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539) ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
tomcat启动 c3p0死锁 ,测试,预发布没问题,生产环境启动c3p0死锁
2020-02-11 18:55:50.449  WARN c     : com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6a749e11 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks! 2020-02-11 18:55:50.452  WARN [C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-AdminTaskTimer] c.m.v.a.ThreadPoolAsynchronousRunner     : com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@6a749e11 -- APPARENT DEADLOCK!!! Complete Status:      Managed Threads: 3     Active Threads: 3     Active Tasks:          com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@258e6714             on thread: C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#0         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@6bc4e1a2             on thread: C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#1         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@146123e0             on thread: C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#2     Pending Tasks:          com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@13c1fbf0         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@45a1985b         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@924a8bc         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@1447f45b         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@8c59358         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@41efa15b         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@6da29092 Pool thread stack traces:     Thread[C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#1,5,main]         java.net.SocketInputStream.socketRead0(Native Method)         java.net.SocketInputStream.socketRead(SocketInputStream.java:116)         java.net.SocketInputStream.read(SocketInputStream.java:170)         java.net.SocketInputStream.read(SocketInputStream.java:141)         com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:100)         com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:143)         com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:173)         com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2954)         com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:560)         com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1014)         com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2255)         com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2106)         com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2090)         com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)         com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)         sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)         sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)         sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)         java.lang.reflect.Constructor.newInstance(Constructor.java:423)         com.mysql.jdbc.Util.handleNewInstance(Util.java:404)         com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)         com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)         com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175)         com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220)         com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206)         com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203)         com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1176)         com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1163)         com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44)         com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1908)         com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696)     Thread[C3P0PooledConnectionPoolManager[identityToken->1hge1bfa8eeb65muaq2al|45f13281]-HelperThread-#0,5,main] <?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <context:property-override location="classpath:config/properties/connection.properties" /> <!-- ================================= 数据源配置 ============================================= --> <bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource"/> <bean id="dataSource101" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--preparedStatement 不会在数据库被 cached导致 连接数的被占用,checkoutOut的时候超时--> <property name="maxStatements" value="0"/> </bean> <bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource"/> <bean id="dataSource3" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--preparedStatement 不会在数据库被 cached导致 连接数的被占用,checkoutOut的时候超时--> <property name="maxStatements" value="0"/> </bean> <!-- define the SqlSessionFactory --> <bean id="sessionFactory1" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource1"/> <property name="configLocation" value="classpath:config/mybatis/mybatis-Configuration.xml"/> <property name="mapperLocations"> <array> <value>classpath*:mapper/*Mapper.xml</value> </array> </property> </bean> <bean id="sessionFactory101" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource101"/> <property name="configLocation" value="classpath:config/mybatis/mybatis-Configuration.xml"/> <property name="mapperLocations"> <array> <value>classpath*:mapper/*Mapper.xml</value> </array> </property> </bean> <bean id="sessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource2"/> <property name="configLocation" value="classpath:config/mybatis/mybatis-Configuration.xml"/> <property name="mapperLocations"> <array> <value>classpath*:mapper/*Mapper.xml</value> </array> </property> </bean> <bean name="transactionManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource1"/> </bean> <bean name="transactionManager101" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource101"/> </bean> <bean name="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource2"/> </bean> <tx:annotation-driven transaction-manager="transactionManager1" /> <tx:annotation-driven transaction-manager="transactionManager101" /> <tx:annotation-driven transaction-manager="transactionManager2" /> <!-- 开启AOP 如果pointcut指向 controller则需要在springmvc的配置文件中配置 --> <aop:aspectj-autoproxy/> <tx:advice id="txAdvice" transaction-manager="transactionManager1"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config expose-proxy="true"> <!-- 第一个*代表所有的返回值类型 第一个.代表子包 第二个*代表所有的类 第三个*代表类所有方法 第一个..代表所有的参数 --> <aop:pointcut id="txPointcut" expression="execution(* app.service..*.*(..))" /> <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice --> <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/> </aop:config> </beans> ##DB config dataSource1.driverClass=com.mysql.jdbc.Driver dataSource1.jdbcUrl=url dataSource1.user= dataSource1.password= dataSource1.testConnectionOnCheckout=true dataSource1.maxPoolSize=200 dataSource1.minPoolSize=10 dataSource1.initialPoolSize=10 dataSource1.checkoutTimeout=30000 dataSource1.maxIdleTime=30 dataSource1.maxStatements=0 dataSource1.maxStatementsPerConnection=0 dataSource101.driverClass=com.mysql.jdbc.Driver dataSource101.jdbcUrl=url dataSource101.user= dataSource101.password= dataSource101.testConnectionOnCheckout=true dataSource101.maxPoolSize=200 dataSource101.minPoolSize=10 dataSource101.initialPoolSize=10 dataSource101.checkoutTimeout=30000 dataSource101.maxIdleTime=30 dataSource101.maxStatements=0 dataSource101.maxStatementsPerConnection=0 dataSource2.driverClass=com.mysql.jdbc.Driver dataSource2.jdbcUrl=jdbc:mysql://localhost:3306/aaa?useSSL=true&useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false dataSource2.user= dataSource2.password= dataSource2.testConnectionOnCheckout=true dataSource2.maxPoolSize=200 dataSource2.minPoolSize=10 dataSource2.initialPoolSize=10 dataSource2.checkoutTimeout=30000 dataSource2.maxIdleTime=30 dataSource2.maxStatements=0 dataSource2.maxStatementsPerConnection=0 dataSource3.driverClass=com.mysql.jdbc.Driver dataSource3.jdbcUrl=jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false dataSource3.user= dataSource3.password= dataSource3.testConnectionOnCheckout=true dataSource3.maxPoolSize=10 dataSource3.minPoolSize=5 dataSource3.initialPoolSize=5 dataSource3.checkoutTimeout=30000 dataSource3.maxIdleTime=30 dataSource3.maxStatements=0 dataSource3.maxStatementsPerConnection=0
连接池的Connection问题
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>项目中使用了proxool数据源,配置了静态创建连接类。</p> <p> </p> <pre name="code" class="java">public class DBConnection { public static Connection getConn() throws Exception{ return DriverManager.getConnection("proxool.db_master"); } public static void closeDB(Connection conn){ try{ if (conn!=null) conn.close(); }catch (Exception e) { // TODO: handle exception } }}</pre> <p> <span style="line-height: 1.5;">那这样使用的时候还需不需要调用Connection.close()方法呢?</span></p> <p>try{conn.close();conn=null;}catch(Exception e){}</p> <p>这个close方法是直接调用了java.sql.Connection.close()方法,这样是不是绕过连接池直接关闭 Conn了呢?</p> <p>如果需要那么Connection就是我手动关闭的,跟连接池没什么关系?<br> 如果不关闭的话那是什么时候关闭呢?<br> 请达人给我解释一下。               </p> </div>
c3p0 连接不释放 请路过的大神过来看看
配置文件如下 <?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:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <!-- 打开Spring的Annotation支持 --> <!-- 设定Spring 去哪些包中找Annotation --> <context:component-scan base-package="com.myd" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${driverClass}" /> <property name="jdbcUrl" value="${jdbcUrl}" /> <property name="user" value="${username}" /> <property name="password" value="${password}" /> <!-- 配置连接池的初始值 --> <property name="acquireIncrement" value="${acquireIncrement}" /> <property name="maxPoolSize" value="${maxPoolSize}" /> <property name="minPoolSize" value="${minPoolSize}" /> <property name="initialPoolSize" value="${initialPoolSize}" /> <property name="maxIdleTime" value="${maxIdleTime}" /> <property name="checkoutTimeout" value="${checkoutTimeout}" /> <property name="autoCommitOnClose" value="${autoCommitOnClose}"></property> <property name="acquireRetryDelay" value="${acquireRetryDelay}" /> <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"></property> <property name="maxStatements" value="${maxStatements}"></property> <property name="numHelperThreads" value="${numHelperThreads}"></property> </bean> <!-- 导入src目录下的c3p0.properties文件 --> <context:property-placeholder location="classpath:c3p0.properties" /> <!--创建Spring的SessionFactory工厂 --> <!-- 如果使用的是Annotation的方式,不能使用LocalSessionFactoryBean,而应该使用 org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 设置Spring取那个包中查找相应的实体类 --> <property name="packagesToScan"> <value>com.myd.entity</value> </property> <property name="hibernateProperties"> <!-- <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> --> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.autoReconnect">true</prop> <prop key="jdbc.use_scrollable_resultset">false</prop> <prop key="hibernate.connection.release_mode">after_statement</prop> <prop key="hibernate.c3p0.validate">true</prop> <prop key="hibernate.c3p0.idle_test_period">30</prop> <prop key="hibernate.c3p0.timeout">30</prop> <prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop> </props> </property> </bean> <!-- 开启HibernateTemplate,并且为其注入SessionFactory 使用HibernateTemplate不太方便的就是要获取session得通过getSessionFactory()方法获取 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置Spring的事务处理 --> <!-- 创建事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置AOP,Spring是通过AOP来进行事务管理的 --> <aop:config> <!-- 设置pointCut表示哪些方法要加入事务处理 --> <!-- 以下的事务是声明在DAO中,但是通常都会在Service来处理多个业务对象逻辑的关系,注入删除,更新等,此时如果在执行了一个步骤之后抛出异常 就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service,这也就是Spring所提供的一个非常方便的工具,声明式事务 --> <aop:pointcut id="allMethods" expression="execution(* com.myd.service.*.*(..))" /> <!-- 通过advisor来确定具体要加入事务控制的方法 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" /> </aop:config> <!-- 配置哪些方法要加入事务控制 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 --> <tx:method name="*" propagation="REQUIRED" read-only="true" /> <!-- 以下方法都是可能设计修改的方法,就无法设置为只读 --> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="5" /> <property name="maxPoolSize" value="50" /> <property name="queueCapacity" value="1000" /> <property name="keepAliveSeconds" value="60" /> </bean> </beans> 这是事务 package com.myd.dao.impl; import java.lang.reflect.ParameterizedType; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.transform.Transformers; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import com.myd.dao.BaseDao; /** * 可以考虑把所有公共的方法都写在baseDAo中,让所有的DAO都继承BaseDao * 这样基本上就实现了大量的基础方法,如果DAO中有逻辑处理特殊的方法,再在具体的实现类中的DAO中创建 * * @author Administrator * * @param <T> */ @Repository("baseDaoImpl") public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> { /** * 此处不能使用setSessionFactory注入,因为setSessionFactory在HibernateDaoSupport * 中已经定义了而且还是final的,不能被覆盖 * * @param sessionFactory */ @Resource(name = "sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } /** * 创建Class的对象来获取泛型的class */ private Class<Object> clz; @SuppressWarnings("unchecked") public Class<Object> getClz() { if (clz == null) { // 获取泛型的Class对象 clz = (Class<Object>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } return clz; } public void add(T t) { getHibernateTemplate().getSessionFactory().openSession(); getHibernateTemplate().save(t); getHibernateTemplate().getSessionFactory().close(); } public void delete(int id) { getHibernateTemplate().getSessionFactory().openSession(); getHibernateTemplate().delete(load(id)); getHibernateTemplate().getSessionFactory().close(); } @SuppressWarnings("deprecation") public void update(T t) { try { getHibernateTemplate().getSessionFactory().openSession() .connection().prepareStatement("SET SQL_SAFE_UPDATES=0") .execute(); } catch (DataAccessResourceFailureException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } getHibernateTemplate().update(t); getHibernateTemplate().getSessionFactory().close(); } 现在的问题是 运行一段时间后,就卡起, 不是报连接数据库关闭 就是 返回空指针 查了以下是连接未释放导致的,我想请教下各位大神 我这样连接没关闭并回到连接池吗?
在spring的配置文件中配置c3p0和在hibernate的配置文件中配置c3p0有什么区别?
在spring的配置文件中配置c3p0和在hibernate的配置文件中配置c3p0有什么区别? 我最近在学习如何配置struts2+spring+hibernate,其中数据库连接池使用c3p0,一开始在hibernate.cfg.xml中添加c3p0连接的信息如下: ``` <property name="hibernate.connection.provider_class"> org.hibernate.c3p0.internal.C3P0ConnectionProvider </property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.timeout">50000</property> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <!-- 当连接池耗尽并接到获得连接的请求,则新增加连接的数量 --> <property name="hibernate.c3p0.acquire_increment">2</property> ``` 然后找网上的帖子,发现很多c3p0都是配置在spring的配置文件中的,如: ``` <!-- 采用c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernate2" /> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="user" value="root" /> <property name="password" value="root" /> <!-- 配置数据库连接池,最大连接数 --> <property name="maxPoolSize" value="20" /> <!-- 配置数据库连接池,最小连接数 --> <property name="minPoolSize" value="1" /> <!-- 指定数据库连接池的初始化连接数 --> <property name="initialPoolSize" value="1" /> <!-- 指定数据库连接池的连接的最大空闲时间 --> <property name="maxIdleTime" value="10" /> </bean> ``` 这两个有什么关系呢?是一个意思?配置了一个地方另一个地方就不用配置了吧?
Druid连接池中取出连接对象的代码
1.从线程中取Connection对象是什么意思? 2.Druid连接池中取连接对象的代码是?
c3p0 连接池异常,哪位大仙解决过
2017-04-13 01:11:45 NewPooledConnection:486 WARN - [c3p0] A PooledConnection that has already signalled a Connection error is still in use! 2017-04-13 01:11:45 NewPooledConnection:487 WARN - [c3p0] Another error has occurred [ java.sql.SQLException: Closed Connection ] which will not be reported to listeners! java.sql.SQLException: Closed Connection at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:145) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:190) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:286) at oracle.jdbc.driver.PhysicalConnection.setAutoCommit(PhysicalConnection.java:1213) at com.mchange.v2.c3p0.impl.NewProxyConnection.setAutoCommit(NewProxyConnection.java:881) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.releaseManagedConnection(JdbcTransaction.java:127) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doRollback(JdbcTransaction.java:170) at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:211) at org.springframework.orm.hibernate4.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:604) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:853) at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:830) at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:503) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:285) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) at com.jm.application.service.impl.SysUserServiceImpl$$EnhancerBySpringCGLIB$$8703f6f2.getEntity(<generated>) at com.jm.application.controller.JfipayReceiveController.payReceive(JfipayReceiveController.java:78) at sun.reflect.GeneratedMethodAccessor50.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.jm.config.JM_Filter.doFilter(JM_Filter.java:68) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) 连接池配置 #default : 0 #配置当连接池所有连接用完时应用程序getConnection的等待时间。为0则无限等待直至有其他连接释放 #或者创建新的连接,不为0则当时间到的时候如果仍没有获得连接,则会抛出SQLException checkout.timeout=600000 #当连接池中的连接用完时,C3P0一次性创建新连接的数目 default : 3 acquireIncrement=20 #用来配置测试连接 preferredTestQuery=select 1 from dual #如果为true,则在close的时候测试连接的有效性 testConnectionOnCheckin=false #用来配置测试空闲连接的间隔时间,测试方式:preferredTestQuery或者automaticTestTable idleConnectionTestPeriod=3000000 #连接池在获得新连接失败时重试的次数,如果小于等于0则无限重试直至连接获得成功 acquireRetryAttempts=0 #default : 1000ms #连接池在获得新连接时的间隔时间 default : 1000 单位ms acquireRetryDelay=1000
hibernate+c3p0连接池,插入数据程序运行一会就卡住
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>程序是一个导入Excel数据的工具,excel中有好几千条数据,但是程序运行一会,每次都是导入24条以后程序就不运行了,程序好像处于挂起状态一样,卡住了,控制台上也不再打印hibernate日志信息,不知道什么原因,有没有会的看一下,谢谢!</p> <p> </p> <p> </p> <p> </p> <p>hibernate.cfg.xml配置如下:</p> <pre name="code" class="xml">&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;!-- Database connection settings --&gt; &lt;property name="connection.driver_class"&gt;oracle.jdbc.driver.OracleDriver&lt;/property&gt; &lt;property name="connection.url"&gt;jdbc:oracle:thin:@127.0.0.1:1521:orcl&lt;/property&gt; &lt;property name="connection.username"&gt;bps&lt;/property&gt; &lt;property name="connection.password"&gt;bps&lt;/property&gt; &lt;!-- SQL dialect --&gt; &lt;property name="dialect"&gt;org.hibernate.dialect.OracleDialect&lt;/property&gt; &lt;!-- Echo all executed SQL to stdout --&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;!-- Disable the second-level cache --&gt; &lt;property name="cache.provider_class"&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt; &lt;!-- C3P0连接池设定 --&gt; &lt;property name="hibernate.connection.provider_class"&gt;org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider&lt;/property&gt; &lt;property name="hibernate.c3p0.max_size"&gt;100&lt;/property&gt; &lt;property name="hibernate.c3p0.min_size"&gt;30&lt;/property&gt; &lt;property name="hibernate.c3p0.timeout"&gt;5000&lt;/property&gt; &lt;property name="hibernate.c3p0.max_statements"&gt;100&lt;/property&gt; &lt;property name="hibernate.c3p0.idle_test_period"&gt;3000&lt;/property&gt; &lt;property name="hibernate.c3p0.acquire_increment"&gt;2&lt;/property&gt; &lt;property name="hibernate.c3p0.validate"&gt;false&lt;/property&gt; &lt;!-- 映射文件 --&gt; ... &lt;/session-factory&gt; &lt;/hibernate-configuration&gt;</pre> <p> </p> <p> </p> </div>
用struts1.2+tomcat5.5+mysql5.1+c3p0连接池开发 出现死机现象
用struts1.2+tomcat5.5+mysql5.1+c3p0连接池开发 出现死机现象 各位朋友,向大家请教一下,我们用struts1.2+tomcat5.5+mysql5.1+c3p0连接池开发一个web应用网站。 现在我们遇到的问题是:现有已经开发的几个模块,部署到linux服务器上,服务器使用的tomcat5.5,运行一段时间就会出现死机的现象,不能登陆及查询(即:数据库操作无响应),刚开始我们初步判断是连接池的原因(因为我们连接池用的单例模式,之前由于考虑不全,出现了两个连接池对象),但是后面我们已经修改了连接池,只有一个连接池对象,再发布测试还是出现这个现象。我们还是不能确定问题出现在哪里, 只是怀疑连接池的问题,我们又做了修改(将c3p0 连接池修改为struts1.2的数据源配置),再次发布到服务器上测试,还是出现相同的问题。 现在我们能推断的问题原因有以下几种情况: 1.连接池问题 (不能确定,应为我们修改了两次连接池,还是出现相同的问题) 2.tomcat 死掉 (不能确定,网上查找了资料,已经修改了tomcat启动参数 设置jvm 的虚拟内存: set JAVA_OPTS=-Xms512m -Xmx512m) 3.mysql 数据库死掉 (不能确定,如果是数据库服务器死掉,但是通过mysql的客户端可以正常操作查询等一些操作) [b]问题补充:[/b] 补充1:Connection,statement都是在应该关闭的地方关闭了的 补充2:没有使用hibernate 补充3:编译没有报错 [b]问题补充:[/b] 补充:程序能够运行一段时间,大概20分钟左右,然后才数据库操作无响应 [b]问题补充:[/b] 我们程序里有两个线程、每隔15分钟扫描一次数据库中表,同时还有用户不停的访问!!麻烦你能否给一个连接池的配置信息!谢谢!!
druid连接池获取连接超时异常
项目使用spring+springmvc+hibernate,数据库使用oracle11.2.0.1.0,允许的最大连接数为300,数据库服务器防火墙是关闭的。项目中有个定时任务(每天凌晨执行)使用jdbcTemplate同步数据。druid连接池异常信息如下: ``` [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-3] WARN com.alibaba.druid.pool.DruidDataSource - get connection timeout retry : 1 [2019-11-02 03:00:02.002] [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-3] ERROR org.quartz.core.JobRunShell - Job DEFAULT.syncSyldDataDetail threw an unhandled Exception: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 350, creating 1 at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:578) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at com.aqkk.task.SyncSyldData.start(SyncSyldData.java:33) ~[classes/:?] at com.aqkk.task.SyncSyldDataJob.executeInternal(SyncSyldDataJob.java:17) ~[classes/:?] at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:75) ~[spring-context-support-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.quartz.core.JobRunShell.run(JobRunShell.java:202) [quartz-2.3.0.jar:?] at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.3.0.jar:?] Caused by: com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 350, creating 1 at com.alibaba.druid.pool.DruidDataSource.getConnectionInternal(DruidDataSource.java:1512) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnectionDirect(DruidDataSource.java:1255) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:5007) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.filter.stat.StatFilter.dataSource_getConnection(StatFilter.java:680) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:5003) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:1233) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:1225) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:90) ~[druid-1.1.10.jar:1.1.10] at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] ... 7 more [2019-11-02 03:00:02.002] [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-3] ERROR org.quartz.core.ErrorLogger - Job (DEFAULT.syncSyldDataDetail threw an exception. org.quartz.SchedulerException: Job threw an unhandled exception. at org.quartz.core.JobRunShell.run(JobRunShell.java:213) [quartz-2.3.0.jar:?] at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.3.0.jar:?] Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 350, creating 1 at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:578) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at com.aqkk.task.SyncSyldData.start(SyncSyldData.java:33) ~[classes/:?] at com.aqkk.task.SyncSyldDataJob.executeInternal(SyncSyldDataJob.java:17) ~[classes/:?] at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:75) ~[spring-context-support-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.0.jar:?] ... 1 more Caused by: com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 350, creating 1 at com.alibaba.druid.pool.DruidDataSource.getConnectionInternal(DruidDataSource.java:1512) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnectionDirect(DruidDataSource.java:1255) ~[druid-1.1.10.jar:1.1.10] ``` druid配置信息如下: ``` <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${db.jdbcUrl}"/> <property name="username" value="${db.user}"/> <property name="password" value="${db.password}"/> <property name="driverClassName" value="${db.driver}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1"/> <property name="minIdle" value="20"/> <property name="maxActive" value="350"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="1000"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="10000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="30000"/> <property name="testWhileIdle" value="true"/> <property name="validationQuery" value="SELECT 1 FROM DUAL"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <!-- 开启Druid的监控统计功能 --> <property name="filters" value="stat" /> </bean> ``` 为啥凌晨执行定时任务获取不到连接,9点上班系统又是正常运行的呢?
java 代理对象 在加入list以后变回了非代理对象,是正常现象么?怎么处理。
本人小白,在学习数据库连接池实现时,为了确保调用者在获取了Connection后,不要直接close。使用动态代理方式创建代理对象,重新处理close函数。在执行中发现,用户在释放了代理对象以后,连接在add进list以后,变回了非代理的ConnectionImpl对象,导致再次取出时,代理作用丢失,请各位帮忙分析一下是怎么回事? ``` import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.util.LinkedList; public class DBPool { private int maxSize;//最大连接数 private int initSize;//初始化连接数 private int cur = 0;//已经使用的连接数 private LinkedList<Connection> pool = new LinkedList<Connection>(); //初始化连接池 public DBPool(int initSize, int maxSize) { this.maxSize = maxSize; this.initSize = initSize; initPool(initSize); } @Override public String toString() { return "DBPool [pool=" + pool + "]"; } //得到正在使用的连接个数 public int getCur() { return cur; } //连接池中连接个数 public int getPoolSize() { return pool.size(); } //初始化连接池方法 public void initPool(int initSize) { for (int i = 0; i < initSize; i++) { pool.add(createConnection()); } } //提供给调用者一个连接 public Connection getPoolConnection() { if (pool.size() > 0) { cur++; return pool.removeFirst(); } else if (cur >= maxSize) { System.out.println("连接已达到最大值"); return null; } else { cur++; return createConnection(); } } public Connection createConnection() { //使用工具类获取数据库连接 Connection con = MysqlUtils.getConnection(); //创建代理对象,代理con的close方法,如果连接池不满,就放入连接池,如果连接池满,则调用原close方法。 Connection proxy = (Connection) Proxy.newProxyInstance(con.getClass().getClassLoader(), new Class[]{Connection.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; //判断是否close方法 if ("close".equals(method.getName())) { // 如果连接池里面连接数<initSize,则直接加入pool if (pool.size() < initSize) { cur--; pool.addLast(con); } else {// 如果连接池>initSize,则直接关闭。 cur--; result = method.invoke(con, args); } //如果不是close方法,则直接调用原函数 } else { result = method.invoke(con, args); } return result; } }); return proxy; } } ``` 测试方法如下: @Test public void testPool() throws SQLException { //初始化连接池,池大小1,最大连接数2 DBPool pool=new DBPool(1, 2); //获取2个连接 Connection[] conn=new Connection[2]; for(int i=0;i<conn.length;i++) { conn[i]=pool.getPoolConnection(); } //释放两个连接,按照代理处理结果,应该是一个放回连接池,一个关闭。 for(int i=0;i<conn.length;i++) { if(conn[i]!=null) { conn[i].close(); conn[i]=null; } } //再次获取2个连接 for(int i=0;i<conn.length;i++) { conn[i]=pool.getPoolConnection(); } //再次释放2个连接 for(int i=0;i<conn.length;i++) { if(conn[i]!=null) { conn[i].close(); conn[i]=null; } } //预期结果应该是当前使用连接cur=0,池中连接数为1. System.out.println("当前使用的连接数:"+pool.getCur()+",当前连接池中连接数:"+pool.getPoolSize()); } 执行后结果如下: 当前使用的连接数:1,当前连接池中连接数:1 ``` 当前结果与预期结果不一致。 经过调试发现: 1、初始化完毕时,链表内容为: pool LinkedList<E> (id=299) [0] $Proxy4 (id=313) 2、第一次获取getPoolConnection(),conn数组内容为: conn Connection[2] (id=322) [0] $Proxy4 (id=307) [1] $Proxy4 (id=331) 3、第一次放回池中,pool链表内容为和conn数组分别为: pool LinkedList<E> (id=293) [0] ConnectionImpl (id=316) conn Connection[2] (id=322) [0] null [1] null 4、 第二次获取getPoolConnection(),conn数组内容为: conn Connection[2] (id=322) [0] ConnectionImpl (id=316) [1] $Proxy4 (id=491) 同时,在调试时也确实在第二次close两个连接时,conn[0].close没有执行代理程序。 不好意思,没有C币,请大家多包涵。
springnvc+mybatis+C3P0连接池,一段时间数据库就崩溃了,求援~
云服务上有三个tomcat服务器,都启动一段时间后报异常,mysql数据库崩溃,求帮助,怎么配置都配置不行 applicationcontext中连接池配置 ``` <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!--连接池中保留的最小连接数。 --> <property name="minPoolSize" value="${minPoolSize}" /> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize" value="${maxPoolSize}" /> <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime" value="${maxIdleTime}" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement" value="${acquireIncrement}" /> <!--c3p0全局的PreparedStatements缓存的大小。如果maxStatements与maxStatementsPerConnection均为0,则缓存不生效,只要有一个不为0,则语句的缓存就能生效。如果默认值:0 --> <property name="maxStatements" value="${maxStatements}" /> <property name="initialPoolSize" value="${initialPoolSize}" /> <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,如设为0则无限期等待。单位毫秒。Default: 0 --> <property name="checkoutTimeout" value="${checkoutTimeout}" /> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}" /> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts" value="${acquireRetryAttempts}" /> <property name="breakAfterAcquireFailure" value="${breakAfterAcquireFailure}" /> <property name="testConnectionOnCheckout" value="${testConnectionOnCheckout}" /> <property name="connectionCustomizerClassName" value="com.tanwuapp.util.handler.UTF8MB4ConnectionCustomizer" /> </bean> ``` ``` minPoolSize=10 <!--连接池中保留的最大连接数。Default: 15 --> maxPoolSize=40 <!--最大空闲时间,30秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> maxIdleTime=30 <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> acquireIncrement=3 <!--c3p0全局的PreparedStatements缓存的大小。如果maxStatements与maxStatementsPerConnection均为0,则缓存不生效,只要有一个不为0,则语句的缓存就能生效。如果默认值: 0--> maxStatements=50 <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。默认值: 0 --> maxStatementsPerConnection=0 initialPoolSize=10 <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,如设为0则无限期等待。单位毫秒。Default: 0 --> checkoutTimeout=10000 <!--每30秒检查所有连接池中的空闲连接。Default: 0 --> idleConnectionTestPeriod=30 <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> acquireRetryAttempts=30 breakAfterAcquireFailure=true testConnectionOnCheckout=false ``` 异常信息: ``` org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.) ### The error may exist in file [/home/webapps/tomcat-1.2.1/tanwuapps/TanWuAppAPI_v1.2.1/WEB-INF/classes/com/tanwuapp/dao/mapper/BasBannerMapper.xml] ### The error may involve com.tanwuapp.dao.BasBannerDao.findAllInfo ### The error occurred while executing a query ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.) at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371) at com.sun.proxy.$Proxy9.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:119) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52) at com.sun.proxy.$Proxy42.findAllInfo(Unknown Source) at com.tanwuapp.service.impl.HomePageServiceImpl.getBannerList(HomePageServiceImpl.java:55) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198) at com.sun.proxy.$Proxy46.getBannerList(Unknown Source) at com.tanwuapp.controller.ProductSearchController.searchHomeBannerData(ProductSearchController.java:78) at com.tanwuapp.controller.ProductSearchController$$FastClassBySpringCGLIB$$1b828f00.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:700) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.cache.interceptor.CacheInterceptor$1.invoke(CacheInterceptor.java:58) at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:211) at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:66) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:633) at com.tanwuapp.controller.ProductSearchController$$EnhancerBySpringCGLIB$$f6dc0725.searchHomeBannerData(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: org.apache.ibatis.exceptions.PersistenceException: ```
御用配置文件方式实现c3p0
运用配置文件方式实现c3p0时总提示找不到合适的驱动,但是用最基本的方式实现c3p0 时可以找到,请教各位大神如何解决。 报错提示如下 ``` java.sql.SQLException: No suitable driver at java.sql.DriverManager.getDriver(DriverManager.java:315) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:285) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:161) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:161) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:147) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:202) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125) at com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44) at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) ``` c3p0-config.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <c3p0-cofig> <default-config> <property name="driverClass">com.mysql.cj.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/edb_71812</property> <property name="user">root</property> <property name="password">root</property> <!--当连接池中的连接耗尽的时候c3p0一次同时获得连接数--> <property name="acquireIncrement">5</property> <!--初始化时获取的连接个数,取值在minPoolSize和maxPoolSize之间--> <property name="initialPoolSize">10</property> <!--连接池中保留的最大连接池个数--> <property name="maxPoolSize">20</property> <!--连接池中保留的最小连接池个数--> <property name="minPoolSize">10</property> </default-config> <named-config name="sqlserver"> <property name="driverClass">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name="jdbcUrl">jdbc:sqlserver://localhost:1433;databaseName=edb_71812</property> <property name="user">sa</property> <property name="password">root</property> <!--当连接池中的连接耗尽的时候c3p0一次同时获得连接数--> <property name="acquireIncrement">5</property> <!--初始化时获取的连接个数,取值在minPoolSize和maxPoolSize之间--> <property name="initialPoolSize">10</property> <!--连接池中保留的最大连接池个数--> <property name="maxPoolSize">20</property> <!--连接池中保留的最小连接池个数--> <property name="minPoolSize">10</property> </named-config> </c3p0-cofig> ``` MysqlJDBCUtil ``` package com.mo.utils; import com.mchange.v2.c3p0.ComboPooledDataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class MysqlJDBCUtil { private static ComboPooledDataSource ds = null; static { // System.setProperty("com.mchange.v2.c3p0.cfg.xml","/java/c3p0-config.xml"); ds = new ComboPooledDataSource(); } public static Connection getConnection() throws SQLException { return ds.getConnection(); } public static void free(Connection conn, PreparedStatement ps, ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ```
使用c3p0连接ORACLE数据库查询不到数据,SQLPLUS执行相同SQL可以查到
搭建一个webservice 使用c3p0连接oracle数据库,在执行查询语句,查询同一条数据的时候,有的时候查询不到结果,而有的时候查询到结果,服务还不报错,在使用SQLPLUS执行该语句的时候每次都能查到结果,求大神帮忙推测一下是什么问题。 使用c3p0创建一个静态的ComboPooledDataSource对象,当需要的时候从这里获取连接 Connection conn = comb.getConnection(); 数据库是按照日期建的分区表,执行查询语句的时候没有按照分区表查询,这会不会有影响。
anaconda安装后,可以正常打开,但在ipython处显示出现错误,请问该如何解决?
本人刚要学习Python,在安装anaconda后出现问题。 错误具体如下: ``` The error is: Traceback (most recent call last): File "C:\Users\manmin\Anaconda3\lib\site‑packages\spyder\plugins\ipythonconsole.py", line 1572, in create_kernel_manager_and_kernel_client kernel_manager.start_kernel(stderr=stderr_handle) File "C:\Users\manmin\Anaconda3\lib\site‑packages\jupyter_client\manager.py", line 240, in start_kernel self.write_connection_file() File "C:\Users\manmin\Anaconda3\lib\site‑packages\jupyter_client\connect.py", line 547, in write_connection_file kernel_name=self.kernel_name File "C:\Users\manmin\Anaconda3\lib\site‑packages\jupyter_client\connect.py", line 212, in write_connection_file with secure_write(fname) as f: File "C:\Users\manmin\Anaconda3\lib\contextlib.py", line 112, in __enter__ return next(self.gen) File "C:\Users\manmin\Anaconda3\lib\site‑packages\jupyter_client\connect.py", line 102, in secure_write with os.fdopen(os.open(fname, open_flag, 0o600), mode) as f: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\manmin\\AppData\\Roaming\\jupyter\\runtime\\kernel�c05551c8d.json' ``` 错误处的地址和和实际文件地址不同的地方有 ‘lib’实际为‘Lab’
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私有的数
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
此博客仅为我业余记录文章所用,发布到此,仅供网友阅读参考,如有侵权,请通知我,我会删掉。 补充 有不少读者留言说本文章没有用,因为天气预报直接打开手机就可以收到了,为何要多此一举发送到邮箱呢!!!那我在这里只能说:因为你没用,所以你没用!!! 这里主要介绍的是思路,不是天气预报!不是天气预报!!不是天气预报!!!天气预报只是用于举例。请各位不要再刚了!!! 下面是我会用到的两个场景: 每日下
面试官问我:什么是消息队列?什么场景需要他?用了会出现什么问题?
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸,打败了无数
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外
大学四年自学走来,这些珍藏的「实用工具/学习网站」我全贡献出来了
知乎高赞:文中列举了互联网一线大厂程序员都在用的工具集合,涉及面非常广,小白和老手都可以进来看看,或许有新收获。
《阿里巴巴开发手册》读书笔记-编程规约
Java编程规约命名风格 命名风格 类名使用UpperCamelCase风格 方法名,参数名,成员变量,局部变量都统一使用lowerCamelcase风格 常量命名全部大写,单词间用下划线隔开, 力求语义表达完整清楚,不要嫌名字长 ...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
你知道的越多,你不知道的越多 点赞再看,养成习惯 本文 GitHub https://github.com/JavaFamily 已收录,有一线大厂面试点思维导图,也整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,希望我们一起有点东西。 前前言 为啥今天有个前前言呢? 因为你们的丙丙啊,昨天有牌面了哟,直接被微信官方推荐,知乎推荐,也就仅仅是还行吧(心里乐开花)
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca
Python爬虫精简步骤1 获取数据
爬虫的工作分为四步: 1.获取数据。爬虫程序会根据我们提供的网址,向服务器发起请求,然后返回数据。 2.解析数据。爬虫程序会把服务器返回的数据解析成我们能读懂的格式。 3.提取数据。爬虫程序再从中提取出我们需要的数据。 4.储存数据。爬虫程序把这些有用的数据保存起来,便于你日后的使用和分析。 这一篇的内容就是:获取数据。 首先,我们将会利用一个强大的库——requests来获取数据。 在电脑上安装
Python绘图,圣诞树,花,爱心 | Turtle篇
1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle() circle.shape('circle') circle.color('red') circle.speed('fastest') circle.up() square = turtle.Turtle()
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东
破14亿,Python分析我国存在哪些人口危机!
2020年1月17日,国家统计局发布了2019年国民经济报告,报告中指出我国人口突破14亿。 猪哥的朋友圈被14亿人口刷屏,但是很多人并没有看到我国复杂的人口问题:老龄化、男女比例失衡、生育率下降、人口红利下降等。 今天我们就来分析一下我们国家的人口数据吧! 更多有趣分析教程,扫描下方二维码关注vx公号「裸睡的猪」 即可查看! 一、背景 1.人口突破14亿 2020年1月17日,国家统计局发布
听说想当黑客的都玩过这个Monyer游戏(1~14攻略)
第零关 进入传送门开始第0关(游戏链接) 请点击链接进入第1关: 连接在左边→ ←连接在右边 看不到啊。。。。(只能看到一堆大佬做完的留名,也能看到菜鸡的我,在后面~~) 直接fn+f12吧 &lt;span&gt;连接在左边→&lt;/span&gt; &lt;a href="first.php"&gt;&lt;/a&gt; &lt;span&gt;←连接在右边&lt;/span&gt; o
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ......
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!
别低估自己的直觉,也别高估自己的智商
所有群全部吵翻天,朋友圈全部沦陷,公众号疯狂转发。这两周没怎么发原创,只发新闻,可能有人注意到了。我不是懒,是文章写了却没发,因为大家的关注力始终在这次的疫情上面,发了也没人看。当然,我...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。   再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。   下文是原回答,希望能对你能有所启发。   如果我说,这个世界上人真的分三六九等,
为什么听过很多道理,依然过不好这一生?
记录学习笔记是一个重要的习惯,不希望学习过的东西成为过眼云烟。做总结的同时也是一次复盘思考的过程。 本文是根据阅读得到 App上《万维钢·精英日课》部分文章后所做的一点笔记和思考。学习是一个系统的过程,思维模型的建立需要相对完整的学习和思考过程。以下观点是在碎片化阅读后总结的一点心得总结。
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合
如何优雅地打印一个Java对象?
你好呀,我是沉默王二,一个和黄家驹一样身高,和刘德华一样颜值的程序员。虽然已经写了十多年的 Java 代码,但仍然觉得自己是个菜鸟(请允许我惭愧一下)。 在一个月黑风高的夜晚,我思前想后,觉得再也不能这么蹉跎下去了。于是痛下决心,准备通过输出的方式倒逼输入,以此来修炼自己的内功,从而进阶成为一名真正意义上的大神。与此同时,希望这些文章能够帮助到更多的读者,让大家在学习的路上不再寂寞、空虚和冷。 ...
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计
Linux 命令(122)—— watch 命令
1.命令简介 2.命令格式 3.选项说明 4.常用示例 参考文献 [1] watch(1) manual
Linux 命令(121)—— cal 命令
1.命令简介 2.命令格式 3.选项说明 4.常用示例 参考文献 [1] cal(1) manual
记jsp+servlet+jdbc实现的新闻管理系统
1.工具:eclipse+SQLyog 2.介绍:实现的内容就是显示新闻的基本信息,然后一个增删改查的操作。 3.数据库表设计 列名 中文名称 数据类型 长度 非空 newsId 文章ID int 11 √ newsTitle 文章标题 varchar 20 √ newsContent 文章内容 text newsStatus 是否审核 varchar 10 news...
Python新型冠状病毒疫情数据自动爬取+统计+发送报告+数据屏幕(三)发送篇
今天介绍的项目是使用 Itchat 发送统计报告 项目功能设计: 定时爬取疫情数据存入Mysql 进行数据分析制作疫情报告 使用itchat给亲人朋友发送分析报告(本文) 基于Django做数据屏幕 使用Tableau做数据分析 来看看最终效果 目前已经完成,预计2月12日前更新 使用 itchat 发送数据统计报告 itchat 是一个基于 web微信的一个框架,但微信官方并不允
相关热词 c# 识别回车 c#生成条形码ean13 c#子控制器调用父控制器 c# 写大文件 c# 浏览pdf c#获取桌面图标的句柄 c# list反射 c# 句柄 进程 c# 倒计时 线程 c# 窗体背景色
立即提问