目錄
一、SpringBoot對JDBC的整合
依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
配置數據庫連接信息
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_jdbc
driver-class-name: com.mysql.jdbc.Driver
測試能否連接上數據庫
@SpringBootTest
class SpringbootJdbcApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource.getConnection());
}
}
springboot默認是使用com.zaxxer.hikari.HikariDataSource
作爲數據源,2.0以下是用org.apache.tomcat.jdbc.pool.DataSource作爲數據源;
數據源的相關配置都在DataSourceProperties
裏面;
自動配置原理
jdbc的相關配置都在org.springframework.boot.autoconfigure.jdbc
包下
參考DataSourceConfiguration
,根據配置創建數據源,默認使用Hikari
連接池;可以使用spring.datasource.type指定自定義的數據源類型;
springboot默認支持的連接池:
- org.apache.commons.dbcp2.BasicDataSource
- com.zaxxer.hikari.HikariDataSource
- org.apache.tomcat.jdbc.pool.DataSource
自定義數據源類型:
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
name = {"spring.datasource.type"}
)
static class Generic {
Generic() {
}
@Bean
DataSource dataSource(DataSourceProperties properties) {
//使用DataSourceBuilder創建數據源,利用反射創建響應type的數據源,並且綁定相關屬性
return properties.initializeDataSourceBuilder().build();
}
}
啓動應用執行sql
SpringBoot在創建連接池後還會運行預定義的SQL腳本文件,具體參考org.springframework.boot.autoconfigure.jdbc.DataSourceInitializationConfiguration
配置類,在該類中註冊了dataSourceInitializerPostProcessor
下面是獲取schema腳本文件的方法
List scripts = this.getScripts(“spring.datasource.schema”, this.properties.getSchema(), “schema”);
可以看出,如果我們沒有在配置文件中配置腳本的具體位置,就會在classpath下找schema-all.sql
和schema.sql
platform獲取的是all,platform可以在配置文件中修改
具體查看createSchema()
方法和initSchema()
方法
initSchema()方法獲取的是data-all.sql
,data.sql
我們也可以在配置文件中配置sql文件的位置
spring:
datasource:
schema:
- classpath:department.sql
- 指定位置
測試:
在類路徑下創建schema.sql
,運行程序查看數據庫是否存在該表
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
程序啓動後發現表並沒有被創建,DEBUG查看以下,發現在運行之前會有一個判斷
上面方法也不知道在幹什麼,反正就是只要是NEVER
和EMBEDDED
就爲true,而DataSourceInitializationMode枚舉類中除了這兩個就剩下ALWAYS了,可以在配置文件中配置爲ALWAYS
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/spring_jdbc
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
schema.sql
:建表語句
data.sql
:插入數據
注意:項目每次啓動都會執行一次sql
二、整合Druid數據源
選擇哪個數據庫連接池:
- DBCP2 是 Appache 基金會下的項目,是最早出現的數據庫連接池 DBCP 的第二個版本。
- C3P0 最早出現時是作爲 Hibernate 框架的默認數據庫連接池而進入市場。
- Druid 是阿里巴巴公司開源的一款數據庫連接池,其特點在於有豐富的附加功能。
- HikariCP 相較而言比較新,它最近兩年纔出現,據稱是速度最快的數據庫連接池。最近更是被 Spring 設置爲默認數據庫連接池。
不選擇 C3P0 的原因:
- C3P0 的 Connection 是異步釋放。這個特性會導致釋放的在某些情況下 Connection 實際上 still in use ,並未真正釋放掉,從而導致連接池中的 Connection 耗完,等待狀況。
- Hibernate 現在對所有數據庫連接池一視同仁,官方不再指定『默認』數據庫連接池。因此 C3P0 就失去了『官方』光環。
不選擇 DBCP2 的原因:
- 相較於 Druid 和 HikariCP,DBCP2 沒有什麼特色功能/賣點。基本上屬於 能用,沒毛病 的情況,地位顯得略有尷尬。
1、在 Spring Boot 項目中加入druid-spring-boot-starter依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
2、在配置文件中指定數據源類型
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_jdbc
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
# schema:
# - classpath:department.sql
# 數據源更改爲druid
type: com.alibaba.druid.pool.DruidDataSource
3、測試類查看使用的數據源
@SpringBootTest
class SpringbootJdbcApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource.getConnection());
}
}
4、配置參數
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_jdbc
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
# schema:
# - classpath:department.sql
# 數據源更改爲druid
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 連接池配置
# 配置初始化大小、最小、最大
initial-size: 1
min-idle: 1
max-active: 20
# 配置獲取連接等待超時的時間
max-wait: 3000
validation-query: SELECT 1 FROM DUAL
test-on-borrow: false
test-on-return: false
test-while-idle: true
pool-prepared-statements: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
filters: stat,wall,slf4j
5、配置Druid的監控
方式一 : 通過配置後臺監控的Servlet
和Filter
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
// 配置Druid的監控(除了下面的方式,也可以在yml中配置)
//1. 配置一個管理後臺的Servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "root");
initParams.put("loginPassword", "1111");
initParams.put("allow", ""); // 默認就是允許所有訪問
// initParams.put("deny", "這裏寫要拒絕訪問的地址");
registrationBean.setInitParameters(initParams);
return registrationBean;
}
//2. 配置一個監控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new WebStatFilter());
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
registrationBean.setInitParameters(initParams);
registrationBean.setUrlPatterns(Arrays.asList("/*"));
return registrationBean;
}
}
方式二: 通過全局配置文件yml
方式
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_jdbc
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
# schema:
# - classpath:department.sql
# 數據源更改爲druid
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 連接池配置
# 配置初始化大小、最小、最大
initial-size: 1
min-idle: 1
max-active: 20
# 配置獲取連接等待超時的時間
max-wait: 3000
validation-query: SELECT 1 FROM DUAL
test-on-borrow: false
test-on-return: false
test-while-idle: true
pool-prepared-statements: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
filters: stat,wall,slf4j
# 配置web監控,默認配置也和下面相同(除用戶名密碼,enabled默認false外),其他可以不配
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: root
allow: 127.0.0.1
後臺頁面,訪問http://localhost:8080/druid/login.html
這樣就可以監控我們通過Druid連接池來進行的請求!