DB数据源之SpringBoot+MyBatis踏坑过程(四)没有使用链接池的后果html
liuyuhang原创,未经容许禁止转载 mysql
系列目录链接spring
DB数据源之SpringBoot+Mybatis踏坑过程实录(一)sql
1.环境说明数据库
1.1.使用springboot手动获取数据源,其中数据源DataSource使用以下代码获取:编程
1 DataSourceBuilder create = DataSourceBuilder.create(); 2 ... 3 4 DataSource source = create.build();
1.2.只使用了这种方式来建立数据源,而且没有配置数据源链接池tomcat
1.3.在springboot1.0中没有配置tomcat数据源链接池springboot
1.4.在springboot2.0中没有配置tomcat数据源链接池,也没有配置HikariCP链接池app
2.报错表现post
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链接池
具体手动配置方案,下次在更!
以上