• SpringBoot整合c3p0、Druid数据库连接池


    1、C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展,同时在Hibernate、Spring项目开发中被广泛应用。修改项目的pom.xml配置文件,添加C3P0依赖支持管理,由于要连接mysql,所以也要加入mysql的依赖包,如下所示:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
     5     https://maven.apache.org/xsd/maven-4.0.0.xsd">
     6 
     7     <modelVersion>4.0.0</modelVersion>
     8     <parent>
     9         <!-- spring-boot-starter-parent就是官方给出的快速构建SpringBoot项目的公共父pom.xml配置文件支持。 -->
    10         <groupId>org.springframework.boot</groupId>
    11         <artifactId>spring-boot-starter-parent</artifactId>
    12         <version>2.3.4.RELEASE</version>
    13         <relativePath /> <!-- lookup parent from repository -->
    14     </parent>
    15 
    16     <groupId>com.bie</groupId>
    17     <artifactId>springboot-01</artifactId>
    18     <version>0.0.1-SNAPSHOT</version>
    19     <name>springboot-01</name>
    20     <description>Demo project for Spring Boot</description>
    21 
    22     <properties>
    23         <java.version>1.8</java.version>
    24         <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
    25     </properties>
    26 
    27     <dependencies>
    28         <dependency>
    29             <groupId>org.springframework.boot</groupId>
    30             <artifactId>spring-boot-starter-web</artifactId>
    31         </dependency>
    32 
    33         <dependency>
    34             <groupId>org.springframework.boot</groupId>
    35             <artifactId>spring-boot-starter-test</artifactId>
    36             <scope>test</scope>
    37             <exclusions>
    38                 <exclusion>
    39                     <groupId>org.junit.vintage</groupId>
    40                     <artifactId>junit-vintage-engine</artifactId>
    41                 </exclusion>
    42             </exclusions>
    43         </dependency>
    44         <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
    45         <dependency>
    46             <groupId>com.mchange</groupId>
    47             <artifactId>c3p0</artifactId>
    48             <version>0.9.5.2</version>
    49         </dependency>
    50         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    51         <dependency>
    52             <groupId>mysql</groupId>
    53             <artifactId>mysql-connector-java</artifactId>
    54             <!-- <version>5.1.12</version> -->
    55         </dependency>
    56         <dependency>
    57             <groupId>org.springframework.boot</groupId>
    58             <artifactId>spring-boot-configuration-processor</artifactId>
    59             <optional>true</optional>
    60         </dependency>
    61     </dependencies>
    62 
    63     <build>
    64         <plugins>
    65             <plugin>
    66                 <groupId>org.springframework.boot</groupId>
    67                 <artifactId>spring-boot-maven-plugin</artifactId>
    68             </plugin>
    69         </plugins>
    70     </build>
    71 
    72 </project>

    然后,更新项目,Maven -> Update Project,修改application.yml配置文件,追加C3P0数据库连接池配置信息。

     1 # 定义c3p0的配置,没有提示可以使用,数据库连接地址
     2 c3p0.jdbcUrl=jdbc:mysql://localhost:3306/biehl?serverTimezone=UTC
     3 # 数据库用户名
     4 c3p0.user=root
     5 # 数据库密码
     6 c3p0.password=123456
     7 # 数据库驱动程序
     8 c3p0.driverClass=com.mysql.jdbc.Driver
     9 # 最小连接数
    10 c3p0.minPoolSize=2
    11 # 最大连接数
    12 c3p0.maxPoolSize=10
    13 # 最大等待时间
    14 c3p0.maxIdleTime=3000
    15 # 初始化连接数
    16 c3p0.initialPoolSize=3

    定义c3p0的配置的时候,没有提示可以使用,数据库连接地址后面要加上?serverTimezone=UTC,不然报下面的错误,如下所示:

    高版本的 spring boot搭配mysql 驱动版本较高时,如 mysql-connector-java:8.0.16,此时 driver-class-name 的值要带 cj(可不带),url 的值要带时区 serverTimezone(要带)。

      1   .   ____          _            __ _ _
      2  /\ / ___'_ __ _ _(_)_ __  __ _    
      3 ( ( )\___ | '_ | '_| | '_ / _` |    
      4  \/  ___)| |_)| | | | | || (_| |  ) ) ) )
      5   '  |____| .__|_| |_|_| |_\__, | / / / /
      6  =========|_|==============|___/=/_/_/_/
      7  :: Spring Boot ::        (v2.3.4.RELEASE)
      8 
      9 2020-11-15 11:17:01.181  INFO 4908 --- [           main] com.bie.Springboot01ApplicationTests     : Starting Springboot01ApplicationTests on DESKTOP-V37QSSE with PID 4908 (started by biehl in E:eclipseeclipseworkspace_springbootspringboot-01)
     10 2020-11-15 11:17:01.182  INFO 4908 --- [           main] com.bie.Springboot01ApplicationTests     : No active profile set, falling back to default profiles: default
     11 2020-11-15 11:17:01.885  INFO 4908 --- [g-Init-Reporter] com.mchange.v2.log.MLog                  : MLog clients using slf4j logging.
     12 2020-11-15 11:17:02.796  INFO 4908 --- [           main] com.mchange.v2.c3p0.C3P0Registry         : Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
     13 2020-11-15 11:17:03.307  INFO 4908 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
     14 2020-11-15 11:17:03.652  INFO 4908 --- [           main] com.bie.Springboot01ApplicationTests     : Started Springboot01ApplicationTests in 2.803 seconds (JVM running for 4.051)
     15 2020-11-15 11:17:03.950  INFO 4908 --- [           main] c.m.v.c.i.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 -> 1hgemn5ad1k0s6dw1kn7og9|3be8821f, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 1hgemn5ad1k0s6dw1kn7og9|3be8821f, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/biehl, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 1800000, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 2, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
     16 Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
     17 2020-11-15 11:17:34.489  WARN 4908 --- [HelperThread-#2] c.m.v2.resourcepool.BasicResourcePool    : com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@2c34448d -- 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: 
     18 
     19 java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
     20     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     21     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     22     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     23     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     24     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     25     at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     26     at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     27     at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     28     at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     29     at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     30     at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     31     at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     32     at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     33     at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     34     at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     35     at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     36     at com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     37     at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     38     at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) [mchange-commons-java-0.2.11.jar:0.2.11]
     39 Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
     40     at sun.reflect.GeneratedConstructorAccessor27.newInstance(Unknown Source) ~[na:na]
     41     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_191]
     42     at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_191]
     43     at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     44     at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     45     at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     46     at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2120) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     47     at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2143) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     48     at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1310) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     49     at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     50     at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     51     ... 12 common frames omitted
     52 
     53 2020-11-15 11:17:34.492  WARN 4908 --- [HelperThread-#2] c.m.v2.resourcepool.BasicResourcePool    : Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool@51a8313b is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests.
     54 2020-11-15 11:17:34.495  WARN 4908 --- [HelperThread-#0] c.m.v2.resourcepool.BasicResourcePool    : com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@bf450d2 -- 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: 
     55 
     56 java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
     57     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     58     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     59     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     60     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     61     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     62     at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     63     at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     64     at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     65     at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     66     at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     67     at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     68     at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     69     at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     70     at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     71     at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     72     at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     73     at com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     74     at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870) ~[c3p0-0.9.5.2.jar:0.9.5.2]
     75     at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) [mchange-commons-java-0.2.11.jar:0.2.11]
     76 Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
     77     at sun.reflect.GeneratedConstructorAccessor27.newInstance(Unknown Source) ~[na:na]
     78     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_191]
     79     at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_191]
     80     at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     81     at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     82     at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     83     at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2120) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     84     at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2143) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     85     at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1310) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     86     at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     87     at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     88     ... 12 common frames omitted
     89 
     90 2020-11-15 11:17:34.495  WARN 4908 --- [HelperThread-#0] c.m.v2.resourcepool.BasicResourcePool    : Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool@51a8313b is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests.
     91 2020-11-15 11:17:34.495  WARN 4908 --- [HelperThread-#1] c.m.v2.resourcepool.BasicResourcePool    : com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@6ed18a76 -- 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: 
     92 
     93 java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
     94     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     95     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     96     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     97     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     98     at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) ~[mysql-connector-java-8.0.21.jar:8.0.21]
     99     at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    100     at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    101     at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    102     at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    103     at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    104     at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175) ~[c3p0-0.9.5.2.jar:0.9.5.2]
    105     at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220) ~[c3p0-0.9.5.2.jar:0.9.5.2]
    106     at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206) ~[c3p0-0.9.5.2.jar:0.9.5.2]
    107     at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203) ~[c3p0-0.9.5.2.jar:0.9.5.2]
    108     at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138) ~[c3p0-0.9.5.2.jar:0.9.5.2]
    109     at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125) ~[c3p0-0.9.5.2.jar:0.9.5.2]
    110     at com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44) ~[c3p0-0.9.5.2.jar:0.9.5.2]
    111     at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870) ~[c3p0-0.9.5.2.jar:0.9.5.2]
    112     at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696) [mchange-commons-java-0.2.11.jar:0.2.11]
    113 Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    114     at sun.reflect.GeneratedConstructorAccessor27.newInstance(Unknown Source) ~[na:na]
    115     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_191]
    116     at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_191]
    117     at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    118     at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    119     at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    120     at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2120) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    121     at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2143) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    122     at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1310) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    123     at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    124     at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826) ~[mysql-connector-java-8.0.21.jar:8.0.21]
    125     ... 12 common frames omitted
    126 
    127 2020-11-15 11:17:34.496  WARN 4908 --- [HelperThread-#1] c.m.v2.resourcepool.BasicResourcePool    : Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool@51a8313b is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests.
    128 2020-11-15 11:17:34.519  INFO 4908 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

    建立C3P0数据源连接池配置类,此时设置的Bean名称为dataSource。

     1 package com.bie.config;
     2 
     3 import javax.sql.DataSource;
     4 
     5 import org.springframework.boot.context.properties.ConfigurationProperties;
     6 import org.springframework.boot.jdbc.DataSourceBuilder;
     7 import org.springframework.context.annotation.Bean;
     8 import org.springframework.context.annotation.Configuration;
     9 
    10 @Configuration
    11 public class C3p0DatasourceConfig {
    12 
    13     // c3p0 连接池
    14     @Bean(name = "dataSource")
    15     @ConfigurationProperties(prefix = "c3p0")
    16     public DataSource dataSource() {
    17         return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
    18     }
    19 
    20 }

    编写Junit测试类,测试当前DataSource配置是否正确。

      1 package com.bie;
      2 
      3 import java.sql.Connection;
      4 import java.sql.PreparedStatement;
      5 import java.sql.ResultSet;
      6 import java.sql.SQLException;
      7 
      8 import javax.sql.DataSource;
      9 
     10 import org.junit.jupiter.api.Test;
     11 import org.junit.runner.RunWith;
     12 import org.springframework.beans.factory.annotation.Autowired;
     13 import org.springframework.boot.test.context.SpringBootTest;
     14 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     15 import org.springframework.test.context.web.WebAppConfiguration;
     16 
     17 @SpringBootTest(classes = Springboot01Application.class) // 定义要测试的Springboot类
     18 @RunWith(SpringJUnit4ClassRunner.class) // 使用Junit进行测试
     19 @WebAppConfiguration // 进行Web应用配置
     20 class Springboot01ApplicationTests {
     21 
     22     @Autowired
     23     private DataSource dataSource; // 注入DataSource对象
     24 
     25     @Test
     26     void testConnection() throws SQLException {
     27         // 获取连接
     28         Connection connection = this.dataSource.getConnection();
     29         System.out.println(connection);
     30 
     31         String sql = "select * from user_info  ";
     32         PreparedStatement ps = connection.prepareStatement(sql);
     33         ResultSet rs = ps.executeQuery();
     34         UserInfo users = null;
     35         if (rs.next()) {
     36             users = new UserInfo();
     37             // 从数据库中获取值设置到实体类的setter方法中
     38             users.setUserId(rs.getInt("user_id"));
     39             users.setUserAccount(rs.getString("user_account"));
     40             users.setUserPw(rs.getString("user_pw"));
     41             users.setUserNumber(rs.getString("user_number"));
     42             users.setUserName(rs.getString("user_name"));
     43             users.setUserAge(rs.getInt("user_age"));
     44             users.setUserSex(rs.getString("user_sex"));
     45             users.setUserMark(rs.getString("user_mark"));
     46             users.setIsMoney(rs.getString("is_money"));
     47             System.out.println(users.toString());
     48         }
     49     }
     50 
     51     // 内部类
     52     class UserInfo {
     53         private Integer userId;// 用户编号
     54         private String userAccount;// 用户账号
     55         private String userPw;// 用户密码
     56         private String userNumber;// 用户学号
     57         private String userName;// 用户姓名
     58         private Integer userAge;// 用户年龄
     59         private String userSex;// 用户性别
     60         private String userMark;// 用户标识,可以使用一张表,完成管理员和用户
     61 
     62         private String isMoney;
     63 
     64         public Integer getUserId() {
     65             return userId;
     66         }
     67 
     68         public void setUserId(Integer userId) {
     69             this.userId = userId;
     70         }
     71 
     72         public String getUserAccount() {
     73             return userAccount;
     74         }
     75 
     76         public void setUserAccount(String userAccount) {
     77             this.userAccount = userAccount;
     78         }
     79 
     80         public String getUserPw() {
     81             return userPw;
     82         }
     83 
     84         public void setUserPw(String userPw) {
     85             this.userPw = userPw;
     86         }
     87 
     88         public String getUserNumber() {
     89             return userNumber;
     90         }
     91 
     92         public void setUserNumber(String userNumber) {
     93             this.userNumber = userNumber;
     94         }
     95 
     96         public String getUserName() {
     97             return userName;
     98         }
     99 
    100         public void setUserName(String userName) {
    101             this.userName = userName;
    102         }
    103 
    104         public Integer getUserAge() {
    105             return userAge;
    106         }
    107 
    108         public void setUserAge(Integer userAge) {
    109             this.userAge = userAge;
    110         }
    111 
    112         public String getUserSex() {
    113             return userSex;
    114         }
    115 
    116         public void setUserSex(String userSex) {
    117             this.userSex = userSex;
    118         }
    119 
    120         public String getUserMark() {
    121             return userMark;
    122         }
    123 
    124         public void setUserMark(String userMark) {
    125             this.userMark = userMark;
    126         }
    127 
    128         public String getIsMoney() {
    129             return isMoney;
    130         }
    131 
    132         public void setIsMoney(String isMoney) {
    133             this.isMoney = isMoney;
    134         }
    135 
    136         @Override
    137         public String toString() {
    138             return "UserInfo [userId=" + userId + ", userAccount=" + userAccount + ", userPw=" + userPw
    139                     + ", userNumber=" + userNumber + ", userName=" + userName + ", userAge=" + userAge + ", userSex="
    140                     + userSex + ", userMark=" + userMark + ", isMoney=" + isMoney + "]";
    141         }
    142 
    143     }
    144 
    145 }

    使用该测试类的时候,如果报下面的错误,在包资源管理器中右键单击您的项目,然后build path,然后configure build path,然后libraries-->add libraries-->junit-->添加就好了。

     1 java.lang.NoClassDefFoundError: org/junit/platform/launcher/core/LauncherFactory
     2     at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.<init>(JUnit5TestLoader.java:31)
     3     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     4     at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
     5     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
     6     at java.lang.reflect.Constructor.newInstance(Unknown Source)
     7     at java.lang.Class.newInstance(Unknown Source)
     8     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createRawTestLoader(RemoteTestRunner.java:367)
     9     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createLoader(RemoteTestRunner.java:362)
    10     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.defaultInit(RemoteTestRunner.java:306)
    11     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.init(RemoteTestRunner.java:221)
    12     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:205)
    13 Caused by: java.lang.ClassNotFoundException: org.junit.platform.launcher.core.LauncherFactory
    14     at java.net.URLClassLoader.findClass(Unknown Source)
    15     at java.lang.ClassLoader.loadClass(Unknown Source)
    16     at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    17     at java.lang.ClassLoader.loadClass(Unknown Source)
    18     ... 11 more

    2、SpringBoot整合Druid数据库连接池,Druid是阿里巴巴推出的一款数据库连接池组件(可以理解为C3P0的下一代产品),也是一个用于大数据实时查询和分析的高容错、高性能开源分布式系统,可高效处理大规模的数据并实现快速查询和分析。

    修改项目的pom.xml文件,引入Druid的相关依赖库,如下所示:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
     5     https://maven.apache.org/xsd/maven-4.0.0.xsd">
     6 
     7     <modelVersion>4.0.0</modelVersion>
     8     <parent>
     9         <!-- spring-boot-starter-parent就是官方给出的快速构建SpringBoot项目的公共父pom.xml配置文件支持。 -->
    10         <groupId>org.springframework.boot</groupId>
    11         <artifactId>spring-boot-starter-parent</artifactId>
    12         <version>2.3.4.RELEASE</version>
    13         <relativePath /> <!-- lookup parent from repository -->
    14     </parent>
    15 
    16     <groupId>com.bie</groupId>
    17     <artifactId>springboot-01</artifactId>
    18     <version>0.0.1-SNAPSHOT</version>
    19     <name>springboot-01</name>
    20     <description>Demo project for Spring Boot</description>
    21 
    22     <properties>
    23         <java.version>1.8</java.version>
    24         <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
    25     </properties>
    26 
    27     <dependencies>
    28         <dependency>
    29             <groupId>org.springframework.boot</groupId>
    30             <artifactId>spring-boot-starter-web</artifactId>
    31         </dependency>
    32 
    33         <dependency>
    34             <groupId>org.springframework.boot</groupId>
    35             <artifactId>spring-boot-starter-test</artifactId>
    36             <scope>test</scope>
    37             <exclusions>
    38                 <exclusion>
    39                     <groupId>org.junit.vintage</groupId>
    40                     <artifactId>junit-vintage-engine</artifactId>
    41                 </exclusion>
    42             </exclusions>
    43         </dependency>
    44         <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
    45         <dependency>
    46             <groupId>com.mchange</groupId>
    47             <artifactId>c3p0</artifactId>
    48             <version>0.9.5.2</version>
    49         </dependency>
    50         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    51         <dependency>
    52             <groupId>mysql</groupId>
    53             <artifactId>mysql-connector-java</artifactId>
    54             <!-- <version>5.1.12</version> -->
    55         </dependency>
    56         <dependency>
    57             <groupId>org.springframework.boot</groupId>
    58             <artifactId>spring-boot-configuration-processor</artifactId>
    59             <optional>true</optional>
    60         </dependency>
    61 
    62         <!-- 引入 Druid 数据源依赖:https://mvnrepository.com/artifact/com.alibaba/druid -->
    63         <dependency>
    64             <groupId>com.alibaba</groupId>
    65             <artifactId>druid</artifactId>
    66             <version>1.1.9</version>
    67         </dependency>
    68     </dependencies>
    69 
    70     <build>
    71         <plugins>
    72             <plugin>
    73                 <groupId>org.springframework.boot</groupId>
    74                 <artifactId>spring-boot-maven-plugin</artifactId>
    75             </plugin>
    76         </plugins>
    77     </build>
    78 
    79 </project>

    修改application.yml配置文件,追加Druid的连接配置,如下所示:

     1 # 配置当前要使用的数据源的操作类型
     2 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
     3 # 配置Mysql的驱动程序类
     4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
     5 # 数据库连接地址
     6 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/biehl
     7 # 数据库用户名称
     8 spring.datasource.username=root
     9 # 数据库密码
    10 spring.datasource.password=123456
    11 # 进行数据库链接池的配置,数据库最小维持连接数
    12 spring.datasource.dbcp2.min-idle=1
    13 # 数据库初始化提供的连接数
    14 spring.datasource.dbcp2.initial-size=1
    15 # 数据库最大维持连接数
    16 spring.datasource.dbcp2.max-total=1
    17 # 等待连接获取的最大超时时间
    18 spring.datasource.dbcp2.max-wait-millis=3000

    建立Druid数据源连接池配置类,此时设置的Bean名称为dataSource。也可以使用@Value手动一个一个将参数注入进来,然后设置,不过使用@ConfigurationProperties 绑定配置文件参数,此注解更加方便。

     1 package com.bie.config;
     2 
     3 import javax.sql.DataSource;
     4 
     5 import org.springframework.boot.context.properties.ConfigurationProperties;
     6 import org.springframework.context.annotation.Bean;
     7 import org.springframework.context.annotation.Configuration;
     8 
     9 import com.alibaba.druid.pool.DruidDataSource;
    10 
    11 @Configuration
    12 public class DruidDataSourceConfiguration {
    13 
    14     /**
    15      * 注入bean
    16      * 
    17      * @return
    18      */
    19     @Bean(name = "dataSource")
    20     // 作用就是将全局配置文件中 前缀为 spring.datasource的属性值注入到
    21     // com.alibaba.druid.pool.DruidDataSource 的同名参数中。
    22     @ConfigurationProperties(prefix = "spring.datasource")
    23     public DataSource dataSource() {
    24         DruidDataSource datasource = new DruidDataSource();
    25         return datasource;
    26     }
    27 
    28 }

    编写Junit测试类,测试当前DataSource配置是否正确。

      1 package com.bie;
      2 
      3 import java.sql.Connection;
      4 import java.sql.PreparedStatement;
      5 import java.sql.ResultSet;
      6 import java.sql.SQLException;
      7 
      8 import javax.sql.DataSource;
      9 
     10 import org.junit.jupiter.api.Test;
     11 import org.junit.runner.RunWith;
     12 import org.springframework.beans.factory.annotation.Autowired;
     13 import org.springframework.boot.test.context.SpringBootTest;
     14 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     15 import org.springframework.test.context.web.WebAppConfiguration;
     16 
     17 @SpringBootTest(classes = Springboot01Application.class) // 定义要测试的Springboot类
     18 @RunWith(SpringJUnit4ClassRunner.class) // 使用Junit进行测试
     19 @WebAppConfiguration // 进行Web应用配置
     20 class Springboot01ApplicationTests {
     21 
     22     @Autowired
     23     private DataSource dataSource; // 注入DataSource对象
     24 
     25     @Test
     26     void testConnection() throws SQLException {
     27         // 获取连接
     28         Connection connection = this.dataSource.getConnection();
     29         System.out.println(connection);
     30 
     31         String sql = "select * from user_info  ";
     32         PreparedStatement ps = connection.prepareStatement(sql);
     33         ResultSet rs = ps.executeQuery();
     34         UserInfo users = null;
     35         if (rs.next()) {
     36             users = new UserInfo();
     37             // 从数据库中获取值设置到实体类的setter方法中
     38             users.setUserId(rs.getInt("user_id"));
     39             users.setUserAccount(rs.getString("user_account"));
     40             users.setUserPw(rs.getString("user_pw"));
     41             users.setUserNumber(rs.getString("user_number"));
     42             users.setUserName(rs.getString("user_name"));
     43             users.setUserAge(rs.getInt("user_age"));
     44             users.setUserSex(rs.getString("user_sex"));
     45             users.setUserMark(rs.getString("user_mark"));
     46             users.setIsMoney(rs.getString("is_money"));
     47             System.out.println(users.toString());
     48         }
     49     }
     50 
     51     // 内部类
     52     class UserInfo {
     53         private Integer userId;// 用户编号
     54         private String userAccount;// 用户账号
     55         private String userPw;// 用户密码
     56         private String userNumber;// 用户学号
     57         private String userName;// 用户姓名
     58         private Integer userAge;// 用户年龄
     59         private String userSex;// 用户性别
     60         private String userMark;// 用户标识,可以使用一张表,完成管理员和用户
     61 
     62         private String isMoney;
     63 
     64         public Integer getUserId() {
     65             return userId;
     66         }
     67 
     68         public void setUserId(Integer userId) {
     69             this.userId = userId;
     70         }
     71 
     72         public String getUserAccount() {
     73             return userAccount;
     74         }
     75 
     76         public void setUserAccount(String userAccount) {
     77             this.userAccount = userAccount;
     78         }
     79 
     80         public String getUserPw() {
     81             return userPw;
     82         }
     83 
     84         public void setUserPw(String userPw) {
     85             this.userPw = userPw;
     86         }
     87 
     88         public String getUserNumber() {
     89             return userNumber;
     90         }
     91 
     92         public void setUserNumber(String userNumber) {
     93             this.userNumber = userNumber;
     94         }
     95 
     96         public String getUserName() {
     97             return userName;
     98         }
     99 
    100         public void setUserName(String userName) {
    101             this.userName = userName;
    102         }
    103 
    104         public Integer getUserAge() {
    105             return userAge;
    106         }
    107 
    108         public void setUserAge(Integer userAge) {
    109             this.userAge = userAge;
    110         }
    111 
    112         public String getUserSex() {
    113             return userSex;
    114         }
    115 
    116         public void setUserSex(String userSex) {
    117             this.userSex = userSex;
    118         }
    119 
    120         public String getUserMark() {
    121             return userMark;
    122         }
    123 
    124         public void setUserMark(String userMark) {
    125             this.userMark = userMark;
    126         }
    127 
    128         public String getIsMoney() {
    129             return isMoney;
    130         }
    131 
    132         public void setIsMoney(String isMoney) {
    133             this.isMoney = isMoney;
    134         }
    135 
    136         @Override
    137         public String toString() {
    138             return "UserInfo [userId=" + userId + ", userAccount=" + userAccount + ", userPw=" + userPw
    139                     + ", userNumber=" + userNumber + ", userName=" + userName + ", userAge=" + userAge + ", userSex="
    140                     + userSex + ", userMark=" + userMark + ", isMoney=" + isMoney + "]";
    141         }
    142 
    143     }
    144 
    145 }

    如果进行连接测试使用的ORM框架的话,需要导入相应ORM框架的依赖支持包。

  • 相关阅读:
    ◆◆0[BAPI]如何修改工单状态-BAPI_ALM_ORDER_MAINTAIN
    ◆◆0[BAPI]如何读取采购订单PO审批状态数据-[BAPI_PO_GETRELINFO]
    ◆◆0[问题解决]开启了adsubcon调用BAPI_GOODSMVT_CREATE创建物料凭证时第一行批次错误
    ◆◆0如何查看ECC系统中配置的PI连接账号
    ◆◆0[问题解决]调用BAPI_ACC_DOCUMENT_POST时报错“被合并的公司 XXXX 和 XXXX 是不同的”
    [问题解决]创建预制发票(BAPI_INCOMINGINVOICE_PARK)时报错”采购凭证的帐户设置00不存在”
    [BAPI]读取设备用户状态和系统状态-BAPI_EQUI_GETSTATUS
    28-高级特性之作用域(2)
    31-高级特性之装饰器(1)
    30-高级特性之闭包(2)
  • 原文地址:https://www.cnblogs.com/biehongli/p/13976181.html
Copyright © 2020-2023  润新知