一、配置环境
-
在选择 dependencies的是增加两个SQL依赖,JDBC API和MySQL Driver
二、配置数据库信息并测试
springboot的默认配置文件是application.properties,可以换成YAML配置,具体操作参考文章:【Spring Boot】配置文件之YAML
- application.yaml配置:
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/hz?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
- springboot测试类测试:@Autowired自动装配
@SpringBootTest
class SpringbootDataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
测试结果:
class com.zaxxer.hikari.HikariDataSource
HikariProxyConnection@189970261 wrapping com.mysql.cj.jdbc.ConnectionImpl@a098d76
- controller类测试:
@RestController
public class JdbcController {
@Autowired
JdbcTemplate template;
@GetMapping("/test")
public List<Map<String, Object>> test(){
List<Map<String, Object>> maps = template.queryForList("select * from blog");
return maps;
}
//数据库的其他增加,删除,修改,全部用template.update(sql,sql语句中需要传的值)
}
访问http://localhost:8080/test页面:
三、Druid数据源
1. 简介
Druid是阿里巴巴开源平台上一个数据库连接池实现,结合了C3PO、DBCP、PROXOOL等DB池的优点,同时加入了日志监控。
Druid可以很好的监控DB池连接和SQL的执行情况,天生就是针对监控而生的DB 连接池。
Spring Boot 2.0以上默认使用Hikari 数据源,接下是我们使用Spring Boot集成Druid数据源,实现数据库监控。
Github:https://github.com/alibaba/druid
2. 使用步骤
- 导入pom.xml依赖:
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
- 修改配置文件:
Spring Boot 2.0以上默认使用Hikari 数据源,我们需要使用Spring Boot集成Druid数据源,实现数据库监控的话,需要在Spring.datasource.type改成Druid,还有一些配置参数:
属性 | 说明 | 建议值 |
---|---|---|
url | 数据库的jdbc连接地址。一般为连接oracle/mysql | mysql : jdbc:mysql://ip:port/dbname?option1&option2&… oracle : jdbc:oracle:thin:@ip:port:oracle_sid |
username | 登录数据库的用户名 | |
password | 登录数据库的用户密码 | |
initialSize | 启动程序时,在连接池中初始化多少个连接 | 10-50已足够 |
maxActive | 连接池中最多支持多少个活动会话 | |
maxWait | 程序向连接池中请求连接时,超过maxWait的值后,认为本次请求失败,即连接池 没有可用连接,单位毫秒,设置-1时表示无限等待 | 100 |
minEvictableIdleTimeMillis | 池中某个连接的空闲时长达到 N 毫秒后, 连接池在下次检查空闲连接时,将回收该连接,要小于防火墙超时设置net.netfilter.nf_conntrack_tcp_timeout_established的设置 | |
timeBetweenEvictionRunsMillis | 检查空闲连接的频率,单位毫秒, 非正整数时表示不进行检查 | |
keepAlive | 程序没有close连接且空闲时长超过 minEvictableIdleTimeMillis,则会执行validationQuery指定的SQL,以保证该程序连接不会池kill掉,其范围不超过minIdle指定的连接个数 | true |
minIdle | 回收空闲连接时,将保证至少有minIdle个连接. 与initialSize相同 | |
removeAbandoned | 要求程序从池中get到连接后, N 秒后必须close,否则druid 会强制回收该连接,不管该连接中是活动还是空闲, 以防止进程不会进行close而霸占连接 | false,当发现程序有未正常close连接时设置为true |
removeAbandonedTimeout | 设置druid 强制回收连接的时限,当程序从池中get到连接开始算起,超过此值后,druid将强制回收该连接,单位秒 | 应大于业务运行最长时间 |
logAbandoned | 当druid强制回收连接后,是否将stack trace 记录到日志中 | true |
testWhileIdle | 当程序请求连接,池在分配连接时,是否先检查该连接是否有效。(高效) | true |
validationQuery | 检查池中的连接是否仍可用的 SQL 语句,drui会连接到数据库执行该SQL, 如果正常返回,则表示连接可用,否则表示连接不可用 | |
testOnBorrow | 程序 申请 连接时,进行连接有效性检查(低效,影响性能) | false |
testOnReturn | 程序 返还 连接时,进行连接有效性检查(低效,影响性能) | false |
poolPreparedStatements | 缓存通过以下两个方法发起的SQL:public PreparedStatement prepareStatement(String sql) public PreparedStatement prepareStatement(String sql,int resultSetType, int resultSetConcurrency) | true |
maxPoolPrepareStatementPerConnectionSize | 每个连接最多缓存多少个SQL 20 | |
filters | 这里配置的是插件,常用的插件有: 监控统计: filter:stat 日志监控: filter:log4j 或者 slf4j 防御SQL注入: filter:wall | stat,wall,slf4j |
connectProperties | 连接属性。比如设置一些连接池统计方面的配置 druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 |
application.yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/hz?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
同时导入log4j依赖pom.xml:
<!--log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
- 让配置文件中的属性生效,同时写好监控后台:
需要写一个DruidConfig.java
@Configuration
public class DruidConfig {
//配置文件中的属性生效
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控:web.xml ServletRegistrationBean
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//后台需要有人登录,账号密码配置
HashMap<String, String> initParameters = new HashMap<>();
//增加配置
initParameters.put("loginUsername","admin");//key固定
initParameters.put("loginPassword","123456");
//允许谁可以访问
initParameters.put("allow","");//第二个参数表示可以允许的用户,不填表示都可以访问
//禁止谁能访问 initParameters.put("","","");参数表示禁止的用户
//设置初始化参数
bean.setInitParameters(initParameters);
return bean;
}
}
- 后台监控:
前面DruidConfig.java配置了后台监控,可以直接访问:http://localhost:8080/druid
用户名和密码对应DruidConfig.java里面的initParameters.put("loginUsername","admin");//key固定
和initParameters.put("loginPassword","123456");
如果执行一条SQL语句,可以实时监控到:
5. 加入过滤器:用于配置web和druid数据源之间的管理关联监控统计
在DruidConfig.java中加入:
//过滤器
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//可以过滤哪些请求
HashMap<String, String> initParameters = new HashMap<>();
//exclusions:这些东西不进行统计,
initParameters.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);
return bean;
}