zoukankan      html  css  js  c++  java
  • DB数据源之SpringBoot+MyBatis踏坑过程(四)没有使用连接池的后果

    DB数据源之SpringBoot+MyBatis踏坑过程(四)没有使用连接池的后果

     

    liuyuhang原创,未经允许禁止转载 

    系列目录连接

    DB数据源之SpringBoot+Mybatis踏坑过程实录(一)

    1.环境说明

      1.1.使用springboot手动获取数据源,其中数据源DataSource使用如下代码获取:

    1 DataSourceBuilder create = DataSourceBuilder.create();
    2 ...
    3 
    4 DataSource source = create.build();

      1.2.只使用了这种方式来创建数据源,并且没有配置数据源连接池

      1.3.在springboot1.0中没有配置tomcat数据源连接池

      1.4.在springboot2.0中没有配置tomcat数据源连接池,也没有配置HikariCP连接池

    2.报错表现

      2.1.部分报错内容如下:

        Error querying database.  Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

        Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

        The last packet successfully received from the server was 14,595,596 milliseconds ago.  The last packet sent successfully to the server was 14,595,612 milliseconds ago.

      2.2.或部分报错内容如下:

        o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

        Data source rejected establishment of connection,  message from server: "Too many connections"

      2.3.在报错内容中,有关于连接池的类,springboot1.0中会出现tomcat的连接池,springboot2.0中会出现Hikari的连接池这两种错误。

      2.4.数据库中现存的连接数量会持续上涨,一直到上涨阈值。查看方法如下:

        cmd-->连接mysql数据库-->输入show status like 'Threads%',结果可能如下:

        

        其中Threads_connected的数量就是上文提到的现存的连接数量,如果配置了连接池,在不断对数据库发送请求的时候,

        该数量虽然会上涨,但是停下来会有消退,同时上涨速度不会那么快的。

        可以持续刷新服务发送请求,然后不断使用此命令查看链接变化,达到某个数字以后,如果报错了,那么查看mysql设置。

        

        该设置应该在mysql根目录中,或者是mysql的data所在目录下,名为my.ini的配置文件,其中有配置最大链接数量,

        可进行调整。

    3.原因分析

        有两种写法实际上中间是有问题的,写法和问题原因如下:

    1 //使用DataSourceBuilder获得数据源额创建者过程中,DataSourceBuilder是有泛型指定的,该泛型没有指定
    2 //create只可以对url,driverClassName,username,password进行设置,并没有相关连接池配置
    3 DataSourceBuilder<?> create = DataSourceBuilder.create();
    4 DataSource source1 = create.build();
    5 //使用DataSourceBuilder获得数据源创建的过程中,使用额是链式编程
    6 DataSource source2 = DataSourceBuilder.create().build();
    7 
    8 //DataSource是一个接口,并非实际的类,因此能set的设置项非常少
    9 public interface DataSource  extends CommonDataSource, Wrapper 

        

        由于上述代码只定义了链接属性,并没有定义连接池,而mysql数据库可以维持的连接数量有限,所以导致本文所指错误。

    4.解决方案

        对于springboot2.0以下的版本,可考虑额外配置一个tomcat连接池

        对于springboot2.0以上的版本,可考虑额外配置一个tomcat连接池之外,还可以配置使用HikariCP连接池

        具体手动配置方案,下次在更!

    以上

  • 相关阅读:
    工厂模式一
    面向对象的简单理解二
    工厂模式三
    线程的简单学习
    nyoj35 表达式求值
    nyoj305 表达式求值
    poj1298 The Hardest Problem Ever
    poj1363 Rails
    hdu2036 改革春风吹满地
    nyoj467 中缀式变后缀式
  • 原文地址:https://www.cnblogs.com/liuyuhangCastle/p/9665032.html
Copyright © 2011-2022 走看看