1.原理实现介绍
本质来说使用连接池是为了节省创建、关闭数据库连接的资源消耗,从而提升访问的性能。底层还是JDBC的调用,jdbc访问多主mysql有提供loadbalace的形式:
jdbc:mysql:loadbalance://[host1][:port],[host2][:port][,[host3][:port]]...[/[database]] »
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
通过上面这种JDBC形式,即可访问多主mysql,但是实际成果中,如果不做任何参数设置,检测失效mysql连接时间非常长,从而降低了数据库访问时间,特加上了以下参数作为性能调优:
roundRobinLoadBalance=true&failOverReadOnly=false&tcpRcvBuf=1024000&loadBalanceStrategy=bestResponseTime&loadBalanceBlacklistTimeout=300000&loadBalancePingTimeout=1000&selfDestructOnPingMaxOperations=200&queryTimeoutKillsConnection=true&loadBalanceValidateConnectionOnSwapServer=true&connectTimeout=1000
JDBC参数详解:
参数名 | 默认值 | 设置值 | 含义 |
---|---|---|---|
roundRobinLoadBalance | false | true | 采用权重轮循均衡算法 |
failOverReadOnly | true | false | 自动重连成功后,连接不设为为只读 |
tcpRcvBuf | 0 | 1024000 | TCP接收缓冲区增大到1MB |
loadBalanceStrategy | random | bestResponseTime | 默认为“random”即随机路由请求,“bestResponseTime”策略负载均衡将请求路由到对上一个事务具有最佳响应时间的主机。 |
loadBalanceBlacklistTimeout | 0 | 300000 | 如果某个节点请求时返回SQLException,那么此host将会被添加到黑名单中,在此后的timeout时间内下一次选择时将不会再被选中。 |
loadBalancePingTimeout | 0 | 1000 | 负责均衡响应ping的超时时间 |
selfDestructOnPingMaxOperations | 0 | 200 | 连接ping不通被关闭时报告阈值 |
queryTimeoutKillsConnection | false | true | 查询超时关闭连接 |
loadBalanceValidateConnectionOnSwapServer | false | true | 当在提交/回滚时交换到新的物理连接时,负载平衡连接显式检查连接处于活动状态 |
connectTimeout | 0 | 1000 | 连接超时时间 |
2.项目配置
引入druid相关的maven依赖
<dependency>
<groupId>log4j2</groupId>
<artifactId>log4j2</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 阿里系的Druid依赖包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
在application.properties/application.yml中添加druid配置文件
spring:
thymeleaf:
mode: html5
encoding: utf-8
suffix: .html
cache: false
# 驱动配置信息
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql:loadbalance://192.168.1.105:3306,192.168.1.107:3306,ip3:3307/test?roundRobinLoadBalance=true&failOverReadOnly=false&tcpRcvBuf=1024000&loadBalanceStrategy=bestResponseTime&loadBalanceBlacklistTimeout=300000&loadBalancePingTimeout=1000&selfDestructOnPingMaxOperations=200&queryTimeoutKillsConnection=true&loadBalanceValidateConnectionOnSwapServer=true&connectTimeout=1000
username: root
password: unew2&2014
driverClassName: com.mysql.jdbc.Driver
# 连接池的配置信息
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j2
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
# connectionProperties: druid.stat.mergeSql: true
druid.stat.slowSqlMillis: 5000
logging:
config: classpath:log4j2/log4j2.xml
添加druidConfig.java作为配置生效文件,并添加druid监控页面 ```java package com.example.demo.configuration;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @Configuration public class DruidConfig {
// 将所有前缀为spring.datasource下的配置项都加载到DataSource中
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
此刻mybatis集成druid已经完成了,可以正常使用druid作为数据连接池去连接数据了。<br />访问http://localhost:8080/druid/login.html 可以查看druid监控页面。<br />参考资料:[https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html](https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html)<br />[https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-j2ee-concepts-managing-load-balanced-connections.html](https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-j2ee-concepts-managing-load-balanced-connections.html)
以上转自:[https://blog.csdn.net/weixin_30344795/article/details/97160475](https://blog.csdn.net/weixin_30344795/article/details/97160475)<br />已做部分修改适应自己项目。
下面是自己的<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/12678011/1616822404750-897a3b67-d87d-4c29-9cad-2a1d96dda9ef.png#align=left&display=inline&height=189&margin=%5Bobject%20Object%5D&name=image.png&originHeight=189&originWidth=295&size=162402&status=done&style=none&width=295)
<a name="9Yat4"></a>
### 3.使用实例
<a name="8VrFA"></a>
#### 配置文件
```yaml
spring:
thymeleaf:
encoding: utf-8
suffix: .html
cache: false
# 驱动配置信息
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql:loadbalance://192.168.1.105:3306,192.168.1.107:3306/test?roundRobinLoadBalance=true&failOverReadOnly=false&tcpRcvBuf=1024000&loadBalanceStrategy=bestResponseTime&loadBalanceBlacklistTimeout=300000&loadBalancePingTimeout=1000&selfDestructOnPingMaxOperations=200&queryTimeoutKillsConnection=true&loadBalanceValidateConnectionOnSwapServer=true&connectTimeout=1000&characterEncoding=UTF-8
username: root
password: 123456
driverClassName: com.mysql.jdbc.Driver
# 连接池的配置信息
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j2
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
# connectionProperties: druid.stat.mergeSql: true
druid.stat.slowSqlMillis: 5000
mybatis:
mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径
configuration:
#org.apache.ibatis.logging.stdout.StdOutImpl 控制台打印sql语句方便调试sql语句执行错误
#org.apache.ibatis.logging.log4j2.Log4j2Impl:这个不在控制台打印查询结果,但是在log4j中打印
log-impl: org.apache.ibatis.logging.log4j2.Log4j2Impl
mapUnderscoreToCamelCase: true # 开启驼峰命名转换法
logging:
config: classpath:log4j2/log4j2.xml
level:
com.example.demo.model: DEBUG