SpringBoot - 整合默认Jdbc与Druid
1.整合JDBC
导入依赖
pom.xml
<!--开启SpringBootJdbc,默认为HikariDataSource源--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--mysql 依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency>
编写配置文件
application.yaml
#jdbc 连接信息
spring:
datasource:
url: jdbc:mysql://localhost:3306/learn?serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
2.整合druid
导入依赖
pom.xml
<!--开启SpringBoot jdbc--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--mysql 依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <!--druid 数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency>
配置文件
application.yaml
spring:
datasource:
#数据源基本配置
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/learn
type: com.alibaba.druid.pool.DruidDataSource
#数据源其他配置
druid:
#配置初始化大小、最小、最大线程数
initialSize: 5
minIdle: 5
#CPU核数+1,也可以大些但不要超过20,数据库加锁时连接过多性能下降
maxActive: 20
#最大等待时间,内网:800,外网:1200(三次握手1s)
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
#配置一个连接在池中最大空间时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
#设置从连接池获取连接时是否检查连接有效性,true检查,false不检查
testOnBorrow: true
#设置从连接池归还连接时是否检查连接有效性,true检查,false不检查
testOnReturn: true
#可以支持PSCache(提升写入、查询效率)
poolPreparedStatements: true
#配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
#保持长连接
keepAlive: true
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
编写配置类
com.levi.springboot_learn.config.DruidConfig
@Configuration public class DruidConfig{ @ConfigurationProperties(prefix="spring.datasource") @Bean public DataSource druid(){ return new DruidDataSource(); } //配置Druid监控 //ServletRegistrationBean替代web.xml配置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","admin"); initParams.put("allow","0.0.0.0");//默认允许所有访问 bean.setInitParameters(initParams); return bean; } //配置一个web监控的filter //FilterRegistrationBean替代web.xml配置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; } }
测试