前言:
去年九月份我和同事在極客時間上買了 丁雪豐 的Spring 全家桶學習,課程總共分爲16章,我已經學了大半部分了,之前是在筆記本上記錄,今天我想記錄在Blog 上 ,分享更多的知識給有需要幫助的人,我會以章節數來作爲文章的內容,原課程講的更詳細,我這裏就一些具體的點做一個總結。
一.Spring 的事務抽象
一致的事務模型
- JDBC/Hibernate/myBatis
- DataSource/JRA
事務抽象的核心接口
PlatformTransactionManager
- DataSourceTransactionManager
- HibernateTransactionManager
- JtaTransactionManager
TransactionDefinition
- Propagation
- Islation
- Timeout
- Read-only status
事務傳播特性
傳播性 | 值 | 描述 |
PROPAGATION_REQUIDED | 0 | 當前有事務就用當前的,沒有就用新的 |
PROPAGATION_SUPPORTS | 1 | 事務可有可無,不是必須的 |
PROPAGATION_MANDATORY | 2 | 當前一定要有事務,不然拋異常 |
PROPAGATION_REQUIRES_NEW | 3 | 無論是否有事務,都起一個新的事務 |
PROPAGATION_NOT_SUPPORTED | 4 | 不支持事務,就按非事務方式運行 |
PROPAGATION_NEVER | 5 | 不支持事務,如果有事務則拋異常 |
PROPAGATION_NESTED | 6 | 當前有事務就在當前事務裏再起一個事務 |
事務隔離特性
隔離性 | 值 | 髒讀 | 不可重複讀 | 幻讀 |
ISOLATION_READ_UNCOMMITTED | 1 | yes | yes | yes |
ISOLATION_READ_COMMITTED | 2 | no | yes | yes |
ISOLATION_REPEATABLE_READ | 3 | no | no | yes |
ISOLATION_SERIALIZABLE | 4 | no | no | no |
編程式事務
TransactionTemplate
- TransactionCallback
- TransactionCallbackWithoutResult
PlatformTransactionManager
- 可以傳入 TransactionDefinition 進行定義
聲明式事務
https://www.cnblogs.com/ooo0/p/11029629.html
基於註解的配置方式
開啓事務註解的方式:
- @EnableTransactionManagement
- <tx:annotation-driven/>
一些配置
- proxyTargetClass
- model
- order
@Transactional
- transactionManager
- propagation
- isolation
- timeout
- readOnly
- 怎麼判斷回滾
二. Spring 的JDBC 異常抽象
Spring 會將數據操作的異常轉換成 DataAccessException
無論使用哪種數據訪問方式,都會使用一樣的異常
Spring 是怎麼認識那些錯誤碼的?
- 通過SQLErrotCodeSQLExceptionTranslator 解析錯誤碼
ErrorCode 定義
- org/springframework/jdbc/support/sql-error-codes.xml
- Classpath下的 sql-error-codes.xml
SpringBoot 定製錯誤碼
三. SpringBoot 常用的註解
可參考:https://blog.csdn.net/tangthh123/article/details/104092510
四. Actuator
URL | 作用 |
/actuator/health | 健康檢查 |
/actuator/beans | 查看容器中的所有Bean |
/actuator/mapping | 查看Web 的URL 映射 |
/actuator/env | 查看環境信息 |
解禁所有的 Endpoint
application.properties 或者 application.yml中 配置參數
management.endpoints.web.exposure.include=*
五. 多數據源.分庫分表.讀寫分離的關係
1.幾種常見情況
- 系統需要訪問幾個完全不同的數據庫,這個時候可以配置倆個數據源
- 系統需要訪問同一個庫的主庫和備庫,也就是要用到讀寫分離的時候, 一個主庫,倆個備庫,單獨配置數據源,讀寫實現分離
- 系統需要訪問一組做了分庫分表的數據庫(垂直拆分 ,水平拆分),儘量用數據庫中間件。
六.事務的本質
Spring 的聲明式事務本質上是通過AOP 來增強了類的功能。
Spring的 AOP 本質上是爲類做了一個代理
- 看似在調用自己的路誒,實際用的是增強後的代理類
問題的解法:
- 訪問增強後的代理類的方法,而非直接訪問自身的方法
七.慢日誌的配置
阿里巴巴數據庫連接池的一些展開說明:
系統屬性配置
- druid.stat.logSlowSql=true
- druid.stat.slowSqlMillis=3000
SpringBoot
- spring.datasource.druid.filter.stat.enabled=true
- spring.datasource.druid,filter.stat.log-slow-sql=true
- spring.datasource.druid.filter.stat.slow-sql-millis=3000