You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 59 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. # 简介
  2. `DBCP`用于创建和管理连接,利用“池”的方式复用连接减少资源开销,和其他连接池一样,也具有连接数控制、连接有效性检测、连接泄露控制、缓存语句等功能。目前,`tomcat`自带的连接池就是`DBCP`,Spring开发组也推荐使用`DBCP`,阿里的`druid`也是参照`DBCP`开发出来的。
  3. `DBCP`除了我们熟知的使用方式外,还支持通过`JNDI`获取数据源,并支持获取`JTA`或`XA`事务中用于`2PC`(两阶段提交)的连接对象,本文也将以例子说明。
  4. 本文将包含以下内容(因为篇幅较长,可根据需要选择阅读):
  5. 1. `DBCP`的使用方法(入门案例说明);
  6. 2. `DBCP`的配置参数详解;
  7. 3. `DBCP`主要源码分析;
  8. 4. `DBCP`其他特性的使用方法,如`JNDI`和`JTA`支持。
  9. # 使用例子
  10. ## 需求
  11. 使用`DBCP`连接池获取连接对象,对用户数据进行简单的增删改查。
  12. ## 工程环境
  13. `JDK`:1.8.0_201
  14. `maven`:3.6.1
  15. `IDE`:eclipse 4.12
  16. `mysql-connector-java`:8.0.15
  17. `mysql`:5.7.28
  18. `DBCP`:2.6.0
  19. ## 主要步骤
  20. 1. 编写`dbcp.properties`,设置数据库连接参数和连接池基本参数等。
  21. 2. 通过`BasicDataSourceFactory`加载`dbcp.properties`,并获得`BasicDataDource`对象。
  22. 3. 通过`BasicDataDource`对象获取`Connection`对象。
  23. 4. 使用`Connection`对象对用户表进行增删改查。
  24. ## 创建项目
  25. 项目类型Maven Project,打包方式war(其实jar也可以,之所以使用war是为了测试`JNDI`)。
  26. ## 引入依赖
  27. ```xml
  28. <!-- junit -->
  29. <dependency>
  30. <groupId>junit</groupId>
  31. <artifactId>junit</artifactId>
  32. <version>4.12</version>
  33. <scope>test</scope>
  34. </dependency>
  35. <!-- dbcp -->
  36. <dependency>
  37. <groupId>org.apache.commons</groupId>
  38. <artifactId>commons-dbcp2</artifactId>
  39. <version>2.6.0</version>
  40. </dependency>
  41. <!-- log4j -->
  42. <dependency>
  43. <groupId>log4j</groupId>
  44. <artifactId>log4j</artifactId>
  45. <version>1.2.17</version>
  46. </dependency>
  47. <!-- mysql驱动的jar包 -->
  48. <dependency>
  49. <groupId>mysql</groupId>
  50. <artifactId>mysql-connector-java</artifactId>
  51. <version>8.0.15</version>
  52. </dependency>
  53. ```
  54. ## 编写dbcp.prperties
  55. 路径`resources`目录下,因为是入门例子,这里仅给出数据库连接参数和连接池基本参数,后面源码会对配置参数进行详细说明。另外,数据库`sql`脚本也在该目录下。
  56. ```properties
  57. #连接基本属性
  58. driverClassName=com.mysql.cj.jdbc.Driver
  59. url=jdbc:mysql://localhost:3306/github_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true
  60. username=root
  61. password=root
  62. #-------------连接池大小和连接超时参数--------------------------------
  63. #初始化连接数量:连接池启动时创建的初始化连接数量
  64. #默认为0
  65. initialSize=0
  66. #最大活动连接数量:连接池在同一时间能够分配的最大活动连接的数量, 如果设置为负数则表示不限制
  67. #默认为8
  68. maxTotal=8
  69. #最大空闲连接:连接池中容许保持空闲状态的最大连接数量,超过的空闲连接将被释放,如果设置为负数表示不限制
  70. #默认为8
  71. maxIdle=8
  72. #最小空闲连接:连接池中容许保持空闲状态的最小连接数量,低于这个数量将创建新的连接,如果设置为0则不创建
  73. #注意:timeBetweenEvictionRunsMillis为正数时,这个参数才能生效。
  74. #默认为0
  75. minIdle=0
  76. #最大等待时间
  77. #当没有可用连接时,连接池等待连接被归还的最大时间(以毫秒计数),超过时间则抛出异常,如果设置为<=0表示无限等待
  78. #默认-1
  79. maxWaitMillis=-1
  80. ```
  81. ## 获取连接池和获取连接
  82. 项目中编写了`JDBCUtils`来初始化连接池、获取连接和释放资源等,具体参见项目源码。
  83. 路径:`cn.zzs.dbcp`
  84. ```java
  85. // 导入配置文件
  86. Properties properties = new Properties();
  87. InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("dbcp.properties");
  88. properties.load(in);
  89. // 根据配置文件内容获得数据源对象
  90. DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
  91. // 获得连接
  92. Connection conn = dataSource.getConnection();
  93. ```
  94. ## 编写测试类
  95. 这里以保存用户为例,路径test目录下的`cn.zzs.dbcp`。
  96. ```java
  97. @Test
  98. public void save() throws SQLException {
  99. // 创建sql
  100. String sql = "insert into demo_user values(null,?,?,?,?,?)";
  101. Connection connection = null;
  102. PreparedStatement statement = null;
  103. try {
  104. // 获得连接
  105. connection = JDBCUtils.getConnection();
  106. // 开启事务设置非自动提交
  107. connection.setAutoCommit(false);
  108. // 获得Statement对象
  109. statement = connection.prepareStatement(sql);
  110. // 设置参数
  111. statement.setString(1, "zzf003");
  112. statement.setInt(2, 18);
  113. statement.setDate(3, new Date(System.currentTimeMillis()));
  114. statement.setDate(4, new Date(System.currentTimeMillis()));
  115. statement.setBoolean(5, false);
  116. // 执行
  117. statement.executeUpdate();
  118. // 提交事务
  119. connection.commit();
  120. } finally {
  121. // 释放资源
  122. JDBCUtils.release(connection, statement, null);
  123. }
  124. }
  125. ```
  126. # 配置文件详解
  127. 这部分内容从网上参照过来,同样的内容发的到处都是,暂时没找到出处。因为内容太过杂乱,而且最新版本更新了不少内容,所以我花了好大功夫才改好,后面找到出处再补上参考资料吧。
  128. ## 基本连接属性
  129. 注意,这里在`url`后面拼接了多个参数用于避免乱码、时区报错问题。 补充下,如果不想加入时区的参数,可以在`mysql`命令窗口执行如下命令:`set global time_zone='+8:00'`。
  130. ```properties
  131. driverClassName=com.mysql.cj.jdbc.Driver
  132. url=jdbc:mysql://localhost:3306/github_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true
  133. username=root
  134. password=root
  135. ```
  136. ## 连接池大小参数
  137. 这几个参数都比较常用,具体设置多少需根据项目调整。
  138. ```properties
  139. #-------------连接池大小和连接超时参数--------------------------------
  140. #初始化连接数量:连接池启动时创建的初始化连接数量
  141. #默认为0
  142. initialSize=0
  143. #最大活动连接数量:连接池在同一时间能够分配的最大活动连接的数量, 如果设置为负数则表示不限制
  144. #默认为8
  145. maxTotal=8
  146. #最大空闲连接:连接池中容许保持空闲状态的最大连接数量,超过的空闲连接将被释放,如果设置为负数表示不限制
  147. #默认为8
  148. maxIdle=8
  149. #最小空闲连接:连接池中容许保持空闲状态的最小连接数量,低于这个数量将创建新的连接,如果设置为0则不创建
  150. #注意:timeBetweenEvictionRunsMillis为正数时,这个参数才能生效。
  151. #默认为0
  152. minIdle=0
  153. #最大等待时间
  154. #当没有可用连接时,连接池等待连接被归还的最大时间(以毫秒计数),超过时间则抛出异常,如果设置为<=0表示无限等待
  155. #默认-1
  156. maxWaitMillis=-1
  157. #连接池创建的连接的默认的数据库名,如果是使用DBCP的XA连接必须设置,不然注册不了多个资源管理器
  158. #defaultCatalog=github_demo
  159. #连接池创建的连接的默认的schema。如果是mysql,这个设置没什么用。
  160. #defaultSchema=github_demo
  161. ```
  162. ## 缓存语句
  163. 缓存语句在`mysql`下建议关闭。
  164. ```properties
  165. #-------------缓存语句--------------------------------
  166. #是否缓存preparedStatement,也就是PSCache。
  167. #PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭
  168. #默认为false
  169. poolPreparedStatements=false
  170. #缓存PreparedStatements的最大个数
  171. #默认为-1
  172. #注意:poolPreparedStatements为true时,这个参数才有效
  173. maxOpenPreparedStatements=-1
  174. #缓存read-only和auto-commit状态。设置为true的话,所有连接的状态都会是一样的。
  175. #默认是true
  176. cacheState=true
  177. ```
  178. ## 连接检查参数
  179. 针对连接失效和连接泄露的问题,建议开启`testWhileIdle`,而不是开启`testOnReturn`或`testOnBorrow`(从性能考虑)。
  180. ```properties
  181. #-------------连接检查情况--------------------------------
  182. #通过SQL查询检测连接,注意必须返回至少一行记录
  183. #默认为空。即会调用Connection的isValid和isClosed进行检测
  184. #注意:如果是oracle数据库的话,应该改为select 1 from dual
  185. validationQuery=select 1 from dual
  186. #SQL检验超时时间
  187. validationQueryTimeout=-1
  188. #是否从池中取出连接前进行检验。
  189. #默认为true
  190. testOnBorrow=true
  191. #是否在归还到池中前进行检验
  192. #默认为false
  193. testOnReturn=false
  194. #是否开启空闲资源回收器。
  195. #默认为false
  196. testWhileIdle=false
  197. #空闲资源的检测周期(单位为毫秒)。
  198. #默认-1。即空闲资源回收器不工作。
  199. timeBetweenEvictionRunsMillis=-1
  200. #做空闲资源回收器时,每次的采样数。
  201. #默认3,单位毫秒。如果设置为-1,就是对所有连接做空闲监测。
  202. numTestsPerEvictionRun=3
  203. #资源池中资源最小空闲时间(单位为毫秒),达到此值后将被移除。
  204. #默认值1000*60*30 = 30分钟
  205. minEvictableIdleTimeMillis=1800000
  206. #资源池中资源最小空闲时间(单位为毫秒),达到此值后将被移除。但是会保证minIdle
  207. #默认值-1
  208. #softMinEvictableIdleTimeMillis=-1
  209. #空闲资源回收策略
  210. #默认org.apache.commons.pool2.impl.DefaultEvictionPolicy
  211. #如果要自定义的话,需要实现EvictionPolicy重写evict方法
  212. evictionPolicyClassName=org.apache.commons.pool2.impl.DefaultEvictionPolicy
  213. #连接最大存活时间。非正数表示不限制
  214. #默认-1
  215. maxConnLifetimeMillis=-1
  216. #当达到maxConnLifetimeMillis被关闭时,是否打印相关消息
  217. #默认true
  218. #注意:maxConnLifetimeMillis设置为正数时,这个参数才有效
  219. logExpiredConnections=true
  220. ```
  221. ## 事务相关参数
  222. 这里的参数主要和事务相关,一般默认就行。
  223. ```properties
  224. #-------------事务相关的属性--------------------------------
  225. #连接池创建的连接的默认的auto-commit状态
  226. #默认为空,由驱动决定
  227. defaultAutoCommit=true
  228. #连接池创建的连接的默认的read-only状态。
  229. #默认值为空,由驱动决定
  230. defaultReadOnly=false
  231. #连接池创建的连接的默认的TransactionIsolation状态
  232. #可用值为下列之一:NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
  233. #默认值为空,由驱动决定
  234. defaultTransactionIsolation=REPEATABLE_READ
  235. #归还连接时是否设置自动提交为true
  236. #默认true
  237. autoCommitOnReturn=true
  238. #归还连接时是否设置回滚事务
  239. #默认true
  240. rollbackOnReturn=true
  241. ```
  242. ## 连接泄漏回收参数
  243. 当我们从连接池获得了连接对象,但因为疏忽或其他原因没有`close`,这个时候这个连接对象就是一个泄露资源。通过配置以下参数可以回收这部分对象。
  244. ```properties
  245. #-------------连接泄漏回收参数--------------------------------
  246. #当未使用的时间超过removeAbandonedTimeout时,是否视该连接为泄露连接并删除(当getConnection()被调用时检测)
  247. #默认为false
  248. #注意:这个机制在(getNumIdle() < 2) and (getNumActive() > (getMaxActive() - 3))时被触发
  249. removeAbandonedOnBorrow=false
  250. #当未使用的时间超过removeAbandonedTimeout时,是否视该连接为泄露连接并删除(空闲evictor检测)
  251. #默认为false
  252. #注意:当空闲资源回收器开启才生效
  253. removeAbandonedOnMaintenance=false
  254. #泄露的连接可以被删除的超时值, 单位秒
  255. #默认为300
  256. removeAbandonedTimeout=300
  257. #标记当Statement或连接被泄露时是否打印程序的stack traces日志。
  258. #默认为false
  259. logAbandoned=true
  260. #这个不是很懂
  261. #默认为false
  262. abandonedUsageTracking=false
  263. ```
  264. ## 其他
  265. 这部分参数比较少用。
  266. ```properties
  267. #-------------其他--------------------------------
  268. #是否使用快速失败机制
  269. #默认为空,由驱动决定
  270. fastFailValidation=false
  271. #当使用快速失败机制时,设置触发的异常码
  272. #多个code用","隔开
  273. #disconnectionSqlCodes
  274. #borrow连接的顺序
  275. #默认true
  276. lifo=true
  277. #每个连接创建时执行的语句
  278. #connectionInitSqls=
  279. #连接参数:例如username、password、characterEncoding等都可以在这里设置
  280. #多个参数用";"隔开
  281. #connectionProperties=
  282. #指定数据源的jmx名。注意,配置了才能注册MBean
  283. jmxName=cn.zzs.jmx:type=BasicDataSource,name=zzs001
  284. #查询超时时间
  285. #默认为空,即根据驱动设置
  286. #defaultQueryTimeout=
  287. #控制PoolGuard是否容许获取底层连接
  288. #默认为false
  289. accessToUnderlyingConnectionAllowed=false
  290. #如果容许则可以使用下面的方式来获取底层物理连接:
  291. # Connection conn = ds.getConnection();
  292. # Connection dconn = ((DelegatingConnection) conn).getInnermostDelegate();
  293. # ...
  294. # conn.close();
  295. ```
  296. # 源码分析
  297. 注意:考虑篇幅和可读性,以下代码经过删减,仅保留所需部分。
  298. ## 创建数据源和连接池
  299. 研究之前,先来看下`BasicDataSource`的`UML`图:
  300. ![BasicDataSource的UML图](https://img2018.cnblogs.com/blog/1731892/201912/1731892-20191228171436263-280030888.png)
  301. 这里介绍下这几个类的作用:
  302. 类名|描述
  303. -|-
  304. `BasicDataSource`|用于满足基本数据库操作需求的数据源
  305. `BasicManagedDataSource`|`BasicDataSource`的子类,用于创建支持`XA`事务或`JTA`事务的连接
  306. `PoolingDataSource`|`BasicDataSource`中实际调用的数据源,可以说`BasicDataSource`只是封装了`PoolingDataSource`
  307. `ManagedDataSource`|`PoolingDataSource`的子类,用于支持`XA`事务或`JTA`事务的连接。是`BasicManagedDataSource`中实际调用的数据源,可以说`BasicManagedDataSource`只是封装了`ManagedDataSource`
  308. 另外,为了支持`JNDI`,`DBCP`也提供了相应的类。
  309. | 类名 | 描述 |
  310. | ----------------------- | ------------------------------------------------------------ |
  311. | `InstanceKeyDataSource` | 用于支持`JDNI`环境的数据源 |
  312. | `PerUserPoolDataSource` | `InstanceKeyDataSource`的子类,针对每个用户会单独分配一个连接池,每个连接池可以设置不同属性。例如以下需求,相比user,`admin`可以创建更多地连接以保证 |
  313. | `SharedPoolDataSource` | `InstanceKeyDataSource`的子类,不同用户共享一个连接池 |
  314. 本文的源码分析仅会涉及到`BasicDataSource`(包含它封装的`PoolingDataSource`),其他的数据源暂时不扩展。
  315. ### BasicDataSource.getConnection()
  316. `BasicDataSourceFactory.createDataSource(Properties)`只是简单地`new`了一个`BasicDataSource`对象并初始化配置参数,此时真正的数据源(`PoolingDataSource`)以及连接池(`GenericObjectPool`)并没有创建,而创建的时机为我们第一次调用`getConnection()`的时候,如下:
  317. ```java
  318. public Connection getConnection() throws SQLException {
  319. return createDataSource().getConnection();
  320. }
  321. ```
  322. 但是,当我们设置了 initialSize > 0,则在`BasicDataSourceFactory.createDataSource(Properties)`时就会完成数据源和连接池的初始化。感谢[moranshouwang](https://home.cnblogs.com/u/901051/)的指正。
  323. 当然,过程都是相同的,只是时机不一样。下面从`BasicDataSource`的`createDataSource()`方法开始分析。
  324. ### BasicDataSource.createDataSource()
  325. 这个方法会创建数据源和连接池,整个过程可以概括为以下几步:
  326. 1. 注册`MBean`,用于支持`JMX`;
  327. 2. 创建连接池对象`GenericObjectPool<PoolableConnection>`;
  328. 3. 创建数据源对象`PoolingDataSource<PoolableConnection>`;
  329. 4. 初始化连接数;
  330. 5. 开启空闲资源回收线程(如果设置`timeBetweenEvictionRunsMillis`为正数)。
  331. ```java
  332. protected DataSource createDataSource() throws SQLException {
  333. if(closed) {
  334. throw new SQLException("Data source is closed");
  335. }
  336. if(dataSource != null) {
  337. return dataSource;
  338. }
  339. synchronized(this) {
  340. if(dataSource != null) {
  341. return dataSource;
  342. }
  343. // 注册MBean,用于支持JMX,这方面的内容不在这里扩展
  344. jmxRegister();
  345. // 创建原生Connection工厂:本质就是持有数据库驱动对象和几个连接参数
  346. final ConnectionFactory driverConnectionFactory = createConnectionFactory();
  347. // 将driverConnectionFactory包装成池化Connection工厂
  348. PoolableConnectionFactory poolableConnectionFactory = createPoolableConnectionFactory(driverConnectionFactory);
  349. // 设置PreparedStatements缓存(其实在这里可以发现,上面创建池化工厂时就设置了缓存,这里没必要再设置一遍)
  350. poolableConnectionFactory.setPoolStatements(poolPreparedStatements);
  351. poolableConnectionFactory.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
  352. // 创建数据库连接池对象GenericObjectPool,用于管理连接
  353. // BasicDataSource将持有GenericObjectPool对象
  354. createConnectionPool(poolableConnectionFactory);
  355. // 创建PoolingDataSource对象
  356. // 该对象持有GenericObjectPool对象的引用
  357. DataSource newDataSource = createDataSourceInstance();
  358. newDataSource.setLogWriter(logWriter);
  359. // 根据我们设置的initialSize创建初始连接
  360. for(int i = 0; i < initialSize; i++) {
  361. connectionPool.addObject();
  362. }
  363. // 开启连接池的evictor线程
  364. startPoolMaintenance();
  365. // 最后BasicDataSource将持有上面创建的PoolingDataSource对象
  366. dataSource = newDataSource;
  367. return dataSource;
  368. }
  369. }
  370. ```
  371. 以上方法涉及到几个类,这里再补充下`UML`图。
  372. ![GenericObjectPool的UML图](https://img2018.cnblogs.com/blog/1731892/201912/1731892-20191228171502877-1140170931.png)
  373. | 类名 | 描述 |
  374. | --------------------------- | ------------------------------------------------------------ |
  375. | `DriverConnectionFactory` | 用于生成原生的Connection对象 |
  376. | `PoolableConnectionFactory` | 用于生成池化的Connection对象,持有`ConnectionFactory`对象的引用 |
  377. | `GenericObjectPool` | 数据库连接池,用于管理连接。持有`PoolableConnectionFactory`对象的引用 |
  378. ## 获取连接对象
  379. 上面已经大致分析了数据源和连接池对象的获取过程,接下来研究下连接对象的获取。在此之前先了解下`DBCP`中几个`Connection`实现类。
  380. ![DelegatingConnection的UML图](https://img2018.cnblogs.com/blog/1731892/201912/1731892-20191228171525594-1114346897.png)
  381. 类名|描述
  382. -|-
  383. `DelegatingConnection`|`Connection`实现类,是以下几个类的父类
  384. `PoolingConnection`|用于包装原生的`Connection`,支持缓存`prepareStatement`和`prepareCall`
  385. `PoolableConnection`|用于包装原生的`PoolingConnection`(如果没有开启`poolPreparedStatements`,则包装的只是原生`Connection`),调用`close()`时只是将连接还给连接池
  386. `PoolableManagedConnection`|`PoolableConnection`的子类,用于包装`ManagedConnection`,支持`JTA`和`XA`事务
  387. `ManagedConnection`|用于包装原生的`Connection`,支持`JTA`和`XA`事务
  388. `PoolGuardConnectionWrapper`|用于包装`PoolableConnection`,当`accessToUnderlyingConnectionAllowed`才能获取底层连接对象。我们获取到的就是这个对象
  389. 另外,这里先概括下获得连接的整个过程:
  390. 1. 如果设置了`removeAbandonedOnBorrow`,达到条件会进行检测;
  391. 2. 从连接池中获取连接,如果没有就通过工厂创建(通过`DriverConnectionFactory`创建原生对象,再通过`PoolableConnectionFactory`包装为池化对象);
  392. 3. 通过工厂重新初始化连接对象;
  393. 4. 如果设置了`testOnBorrow`或者`testOnCreate`,会通过工厂校验连接有效性;
  394. 5. 使用`PoolGuardConnectionWrapper`包装连接对象,并返回给客户端
  395. ### PoolingDataSource.getConnection()
  396. 前面已经说过,`BasicDataSource`本质上是调用`PoolingDataSource`的方法来获取连接,所以这里从`PoolingDataSource.getConnection()`开始研究。
  397. 以下代码可知,该方法会从连接池中“借出”连接。
  398. ```java
  399. public Connection getConnection() throws SQLException {
  400. // 这个泛型C指的是PoolableConnection对象
  401. // 调用的是GenericObjectPool的方法返回PoolableConnection对象,这个方法后面会展开
  402. final C conn = pool.borrowObject();
  403. if (conn == null) {
  404. return null;
  405. }
  406. // 包装PoolableConnection对象,当accessToUnderlyingConnectionAllowed为true时,可以使用底层连接
  407. return new PoolGuardConnectionWrapper<>(conn);
  408. }
  409. ```
  410. ### GenericObjectPool.borrowObject()
  411. `GenericObjectPool`是一个很简练的类,里面涉及到的属性设置和锁机制都涉及得非常巧妙。
  412. ```java
  413. // 存放着连接池所有的连接对象(但不包含已经释放的)
  414. private final Map<IdentityWrapper<T>, PooledObject<T>> allObjects =
  415. new ConcurrentHashMap<>();
  416. // 存放着空闲连接对象的阻塞队列
  417. private final LinkedBlockingDeque<PooledObject<T>> idleObjects;
  418. // 为n>1表示当前有n个线程正在创建新连接对象
  419. private long makeObjectCount = 0;
  420. // 创建连接对象时所用的锁
  421. private final Object makeObjectCountLock = new Object();
  422. // 连接对象创建总数量
  423. private final AtomicLong createCount = new AtomicLong(0);
  424. public T borrowObject() throws Exception {
  425. // 如果我们设置了连接获取等待时间,“借出”过程就必须在指定时间内完成
  426. return borrowObject(getMaxWaitMillis());
  427. }
  428. public T borrowObject(final long borrowMaxWaitMillis) throws Exception {
  429. // 校验连接池是否打开状态
  430. assertOpen();
  431. // 如果设置了removeAbandonedOnBorrow,达到触发条件是会遍历所有连接,未使用时长超过removeAbandonedTimeout的将被释放掉(一般可以检测出泄露连接)
  432. final AbandonedConfig ac = this.abandonedConfig;
  433. if (ac != null && ac.getRemoveAbandonedOnBorrow() &&
  434. (getNumIdle() < 2) &&
  435. (getNumActive() > getMaxTotal() - 3) ) {
  436. removeAbandoned(ac);
  437. }
  438. PooledObject<T> p = null;
  439. // 连接数达到maxTotal是否阻塞等待
  440. final boolean blockWhenExhausted = getBlockWhenExhausted();
  441. boolean create;
  442. final long waitTime = System.currentTimeMillis();
  443. // 如果获取的连接对象为空,会再次进入获取
  444. while (p == null) {
  445. create = false;
  446. // 获取空闲队列的第一个元素,如果为空就试图创建新连接
  447. p = idleObjects.pollFirst();
  448. if (p == null) {
  449. // 后面分析这个方法
  450. p = create();
  451. if (p != null) {
  452. create = true;
  453. }
  454. }
  455. // 连接数达到maxTotal且暂时没有空闲连接,这时需要阻塞等待,直到获得空闲队列中的连接或等待超时
  456. if (blockWhenExhausted) {
  457. if (p == null) {
  458. if (borrowMaxWaitMillis < 0) {
  459. // 无限等待
  460. p = idleObjects.takeFirst();
  461. } else {
  462. // 等待maxWaitMillis
  463. p = idleObjects.pollFirst(borrowMaxWaitMillis,
  464. TimeUnit.MILLISECONDS);
  465. }
  466. }
  467. // 这个时候还是没有就只能抛出异常
  468. if (p == null) {
  469. throw new NoSuchElementException(
  470. "Timeout waiting for idle object");
  471. }
  472. } else {
  473. if (p == null) {
  474. throw new NoSuchElementException("Pool exhausted");
  475. }
  476. }
  477. // 如果连接处于空闲状态,会修改连接的state、lastBorrowTime、lastUseTime、borrowedCount等,并返回true
  478. if (!p.allocate()) {
  479. p = null;
  480. }
  481. if (p != null) {
  482. // 利用工厂重新初始化连接对象,这里会去校验连接存活时间、设置lastUsedTime、及其他初始参数
  483. try {
  484. factory.activateObject(p);
  485. } catch (final Exception e) {
  486. try {
  487. destroy(p);
  488. } catch (final Exception e1) {
  489. // Ignore - activation failure is more important
  490. }
  491. p = null;
  492. if (create) {
  493. final NoSuchElementException nsee = new NoSuchElementException(
  494. "Unable to activate object");
  495. nsee.initCause(e);
  496. throw nsee;
  497. }
  498. }
  499. // 根据设置的参数,判断是否检测连接有效性
  500. if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) {
  501. boolean validate = false;
  502. Throwable validationThrowable = null;
  503. try {
  504. // 这里会去校验连接的存活时间是否超过maxConnLifetimeMillis,以及通过SQL去校验执行时间
  505. validate = factory.validateObject(p);
  506. } catch (final Throwable t) {
  507. PoolUtils.checkRethrow(t);
  508. validationThrowable = t;
  509. }
  510. // 如果校验不通过,会释放该对象
  511. if (!validate) {
  512. try {
  513. destroy(p);
  514. destroyedByBorrowValidationCount.incrementAndGet();
  515. } catch (final Exception e) {
  516. // Ignore - validation failure is more important
  517. }
  518. p = null;
  519. if (create) {
  520. final NoSuchElementException nsee = new NoSuchElementException(
  521. "Unable to validate object");
  522. nsee.initCause(validationThrowable);
  523. throw nsee;
  524. }
  525. }
  526. }
  527. }
  528. }
  529. // 更新borrowedCount、idleTimes和waitTimes
  530. updateStatsBorrow(p, System.currentTimeMillis() - waitTime);
  531. return p.getObject();
  532. }
  533. ```
  534. ### GenericObjectPool.create()
  535. 这里在创建连接对象时采用的锁机制非常值得学习,简练且高效。
  536. ```java
  537. private PooledObject<T> create() throws Exception {
  538. int localMaxTotal = getMaxTotal();
  539. if (localMaxTotal < 0) {
  540. localMaxTotal = Integer.MAX_VALUE;
  541. }
  542. final long localStartTimeMillis = System.currentTimeMillis();
  543. final long localMaxWaitTimeMillis = Math.max(getMaxWaitMillis(), 0);
  544. // 创建标识:
  545. // - TRUE: 调用工厂创建返回对象
  546. // - FALSE: 直接返回null
  547. // - null: 继续循环
  548. Boolean create = null;
  549. while (create == null) {
  550. synchronized (makeObjectCountLock) {
  551. final long newCreateCount = createCount.incrementAndGet();
  552. if (newCreateCount > localMaxTotal) {
  553. // 当前池已经达到maxTotal,或者有另外一个线程正在试图创建一个新的连接使之达到容量极限
  554. createCount.decrementAndGet();
  555. if (makeObjectCount == 0) {
  556. // 连接池确实已达到容量极限
  557. create = Boolean.FALSE;
  558. } else {
  559. // 当前另外一个线程正在试图创建一个新的连接使之达到容量极限,此时需要等待
  560. makeObjectCountLock.wait(localMaxWaitTimeMillis);
  561. }
  562. } else {
  563. // 当前连接池容量未到达极限,可以继续创建连接对象
  564. makeObjectCount++;
  565. create = Boolean.TRUE;
  566. }
  567. }
  568. // 当达到maxWaitTimeMillis时不创建连接对象,直接退出循环
  569. if (create == null &&
  570. (localMaxWaitTimeMillis > 0 &&
  571. System.currentTimeMillis() - localStartTimeMillis >= localMaxWaitTimeMillis)) {
  572. create = Boolean.FALSE;
  573. }
  574. }
  575. if (!create.booleanValue()) {
  576. return null;
  577. }
  578. final PooledObject<T> p;
  579. try {
  580. // 调用工厂创建对象,后面对这个方法展开分析
  581. p = factory.makeObject();
  582. } catch (final Throwable e) {
  583. createCount.decrementAndGet();
  584. throw e;
  585. } finally {
  586. synchronized (makeObjectCountLock) {
  587. // 创建标识-1
  588. makeObjectCount--;
  589. // 唤醒makeObjectCountLock锁住的对象
  590. makeObjectCountLock.notifyAll();
  591. }
  592. }
  593. final AbandonedConfig ac = this.abandonedConfig;
  594. if (ac != null && ac.getLogAbandoned()) {
  595. p.setLogAbandoned(true);
  596. // TODO: in 3.0, this can use the method defined on PooledObject
  597. if (p instanceof DefaultPooledObject<?>) {
  598. ((DefaultPooledObject<T>) p).setRequireFullStackTrace(ac.getRequireFullStackTrace());
  599. }
  600. }
  601. // 连接数量+1
  602. createdCount.incrementAndGet();
  603. // 将创建的对象放入allObjects
  604. allObjects.put(new IdentityWrapper<>(p.getObject()), p);
  605. return p;
  606. }
  607. ```
  608. ### PoolableConnectionFactory.makeObject()
  609. ```java
  610. public PooledObject<PoolableConnection> makeObject() throws Exception {
  611. // 创建原生的Connection对象
  612. Connection conn = connectionFactory.createConnection();
  613. if (conn == null) {
  614. throw new IllegalStateException("Connection factory returned null from createConnection");
  615. }
  616. try {
  617. // 执行我们设置的connectionInitSqls
  618. initializeConnection(conn);
  619. } catch (final SQLException sqle) {
  620. // Make sure the connection is closed
  621. try {
  622. conn.close();
  623. } catch (final SQLException ignore) {
  624. // ignore
  625. }
  626. // Rethrow original exception so it is visible to caller
  627. throw sqle;
  628. }
  629. // 连接索引+1
  630. final long connIndex = connectionIndex.getAndIncrement();
  631. // 如果设置了poolPreparedStatements,则创建包装连接为PoolingConnection对象
  632. if (poolStatements) {
  633. conn = new PoolingConnection(conn);
  634. final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
  635. config.setMaxTotalPerKey(-1);
  636. config.setBlockWhenExhausted(false);
  637. config.setMaxWaitMillis(0);
  638. config.setMaxIdlePerKey(1);
  639. config.setMaxTotal(maxOpenPreparedStatements);
  640. if (dataSourceJmxObjectName != null) {
  641. final StringBuilder base = new StringBuilder(dataSourceJmxObjectName.toString());
  642. base.append(Constants.JMX_CONNECTION_BASE_EXT);
  643. base.append(Long.toString(connIndex));
  644. config.setJmxNameBase(base.toString());
  645. config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
  646. } else {
  647. config.setJmxEnabled(false);
  648. }
  649. final PoolingConnection poolingConn = (PoolingConnection) conn;
  650. final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>(
  651. poolingConn, config);
  652. poolingConn.setStatementPool(stmtPool);
  653. poolingConn.setCacheState(cacheState);
  654. }
  655. // 用于注册连接到JMX
  656. ObjectName connJmxName;
  657. if (dataSourceJmxObjectName == null) {
  658. connJmxName = null;
  659. } else {
  660. connJmxName = new ObjectName(
  661. dataSourceJmxObjectName.toString() + Constants.JMX_CONNECTION_BASE_EXT + connIndex);
  662. }
  663. // 创建PoolableConnection对象
  664. final PoolableConnection pc = new PoolableConnection(conn, pool, connJmxName, disconnectionSqlCodes,
  665. fastFailValidation);
  666. pc.setCacheState(cacheState);
  667. // 包装成连接池所需的对象
  668. return new DefaultPooledObject<>(pc);
  669. }
  670. ```
  671. ## 空闲对象回收器Evictor
  672. 以上基本已分析完连接对象的获取过程,下面再研究下空闲对象回收器。前面已经讲到当创建完数据源对象时会开启连接池的`evictor`线程,所以我们从`BasicDataSource.startPoolMaintenance()`开始分析。
  673. ### BasicDataSource.startPoolMaintenance()
  674. 前面说过`timeBetweenEvictionRunsMillis`为非正数时不会开启开启空闲对象回收器,从以下代码可以理解具体逻辑。
  675. ```java
  676. protected void startPoolMaintenance() {
  677. // 只有timeBetweenEvictionRunsMillis为正数,才会开启空闲对象回收器
  678. if (connectionPool != null && timeBetweenEvictionRunsMillis > 0) {
  679. connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  680. }
  681. }
  682. ```
  683. ### BaseGenericObjectPool.setTimeBetweenEvictionRunsMillis(long)
  684. 这个`BaseGenericObjectPool`是上面说到的`GenericObjectPool`的父类。
  685. ```java
  686. public final void setTimeBetweenEvictionRunsMillis(
  687. final long timeBetweenEvictionRunsMillis) {
  688. // 设置回收线程运行间隔时间
  689. this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  690. // 继续调用本类的方法,下面继续进入方法分析
  691. startEvictor(timeBetweenEvictionRunsMillis);
  692. }
  693. ```
  694. ### BaseGenericObjectPool.startEvictor(long)
  695. 这里会去定义一个`Evictor`对象,这个其实是一个`Runnable`对象,后面会讲到。
  696. ```java
  697. final void startEvictor(final long delay) {
  698. synchronized (evictionLock) {
  699. if (null != evictor) {
  700. EvictionTimer.cancel(evictor, evictorShutdownTimeoutMillis, TimeUnit.MILLISECONDS);
  701. evictor = null;
  702. evictionIterator = null;
  703. }
  704. // 创建回收器任务,并执行定时调度
  705. if (delay > 0) {
  706. evictor = new Evictor();
  707. EvictionTimer.schedule(evictor, delay, delay);
  708. }
  709. }
  710. }
  711. ```
  712. ### EvictionTimer.schedule(Evictor, long, long)
  713. `DBCP`是使用`ScheduledThreadPoolExecutor`来实现回收器的定时检测。 涉及到`ThreadPoolExecutor`为`JDK`自带的`api`,这里不再深入分析线程池如何实现定时调度。感兴趣的朋友可以复习下常用的几款线程池。
  714. ```java
  715. static synchronized void schedule(
  716. final BaseGenericObjectPool<?>.Evictor task, final long delay, final long period)
  717. if (null == executor) {
  718. // 创建线程池,队列为DelayedWorkQueue,corePoolSize为1,maximumPoolSize为无限大
  719. executor = new ScheduledThreadPoolExecutor(1, new EvictorThreadFactory());
  720. // 当任务被取消的同时从等待队列中移除
  721. executor.setRemoveOnCancelPolicy(true);
  722. }
  723. // 设置任务定时调度
  724. final ScheduledFuture<?> scheduledFuture =
  725. executor.scheduleWithFixedDelay(task, delay, period, TimeUnit.MILLISECONDS);
  726. task.setScheduledFuture(scheduledFuture);
  727. }
  728. ```
  729. ### BaseGenericObjectPool.Evictor
  730. `Evictor`是`BaseGenericObjectPool`的内部类,实现了`Runnable`接口,这里看下它的run方法。
  731. ```java
  732. class Evictor implements Runnable {
  733. private ScheduledFuture<?> scheduledFuture;
  734. @Override
  735. public void run() {
  736. final ClassLoader savedClassLoader =
  737. Thread.currentThread().getContextClassLoader();
  738. try {
  739. // 确保回收器使用的类加载器和工厂对象的一样
  740. if (factoryClassLoader != null) {
  741. final ClassLoader cl = factoryClassLoader.get();
  742. if (cl == null) {
  743. cancel();
  744. return;
  745. }
  746. Thread.currentThread().setContextClassLoader(cl);
  747. }
  748. try {
  749. // 回收符合条件的对象,后面继续扩展
  750. evict();
  751. } catch(final Exception e) {
  752. swallowException(e);
  753. } catch(final OutOfMemoryError oome) {
  754. // Log problem but give evictor thread a chance to continue
  755. // in case error is recoverable
  756. oome.printStackTrace(System.err);
  757. }
  758. try {
  759. // 确保最小空闲对象
  760. ensureMinIdle();
  761. } catch (final Exception e) {
  762. swallowException(e);
  763. }
  764. } finally {
  765. Thread.currentThread().setContextClassLoader(savedClassLoader);
  766. }
  767. }
  768. void setScheduledFuture(final ScheduledFuture<?> scheduledFuture) {
  769. this.scheduledFuture = scheduledFuture;
  770. }
  771. void cancel() {
  772. scheduledFuture.cancel(false);
  773. }
  774. }
  775. ```
  776. ### GenericObjectPool.evict()
  777. 这里的回收过程包括以下四道校验:
  778. 1. 按照`evictionPolicy`校验`idleSoftEvictTime`、`idleEvictTime`;
  779. 2. 利用工厂重新初始化样本,这里会校验`maxConnLifetimeMillis`(`testWhileIdle`为true);
  780. 3. 校验`maxConnLifetimeMillis`和`validationQueryTimeout`(`testWhileIdle`为true);
  781. 4. 校验所有连接的未使用时间是否超过r`emoveAbandonedTimeout`(`removeAbandonedOnMaintenance`为true)。
  782. ```java
  783. public void evict() throws Exception {
  784. // 校验当前连接池是否关闭
  785. assertOpen();
  786. if (idleObjects.size() > 0) {
  787. PooledObject<T> underTest = null;
  788. // 介绍参数时已经讲到,这个evictionPolicy我们可以自定义
  789. final EvictionPolicy<T> evictionPolicy = getEvictionPolicy();
  790. synchronized (evictionLock) {
  791. final EvictionConfig evictionConfig = new EvictionConfig(
  792. getMinEvictableIdleTimeMillis(),
  793. getSoftMinEvictableIdleTimeMillis(),
  794. getMinIdle());
  795. final boolean testWhileIdle = getTestWhileIdle();
  796. // 获取我们指定的样本数,并开始遍历
  797. for (int i = 0, m = getNumTests(); i < m; i++) {
  798. if (evictionIterator == null || !evictionIterator.hasNext()) {
  799. evictionIterator = new EvictionIterator(idleObjects);
  800. }
  801. if (!evictionIterator.hasNext()) {
  802. // Pool exhausted, nothing to do here
  803. return;
  804. }
  805. try {
  806. underTest = evictionIterator.next();
  807. } catch (final NoSuchElementException nsee) {
  808. // 当前样本正被另一个线程借出
  809. i--;
  810. evictionIterator = null;
  811. continue;
  812. }
  813. // 判断如果样本是空闲状态,设置为EVICTION状态
  814. // 如果不是,说明另一个线程已经借出了这个样本
  815. if (!underTest.startEvictionTest()) {
  816. i--;
  817. continue;
  818. }
  819. boolean evict;
  820. try {
  821. // 调用回收策略来判断是否回收该样本,按照默认策略,以下情况都会返回true:
  822. // 1. 样本空闲时间大于我们设置的idleSoftEvictTime,且当前池中空闲连接数量>minIdle
  823. // 2. 样本空闲时间大于我们设置的idleEvictTime
  824. evict = evictionPolicy.evict(evictionConfig, underTest,
  825. idleObjects.size());
  826. } catch (final Throwable t) {
  827. PoolUtils.checkRethrow(t);
  828. swallowException(new Exception(t));
  829. evict = false;
  830. }
  831. // 如果需要回收,则释放这个样本
  832. if (evict) {
  833. destroy(underTest);
  834. destroyedByEvictorCount.incrementAndGet();
  835. } else {
  836. // 如果设置了testWhileIdle,会
  837. if (testWhileIdle) {
  838. boolean active = false;
  839. try {
  840. // 利用工厂重新初始化样本,这里会校验maxConnLifetimeMillis
  841. factory.activateObject(underTest);
  842. active = true;
  843. } catch (final Exception e) {
  844. // 抛出异常标识校验不通过,释放样本
  845. destroy(underTest);
  846. destroyedByEvictorCount.incrementAndGet();
  847. }
  848. if (active) {
  849. // 接下来会校验maxConnLifetimeMillis和validationQueryTimeout
  850. if (!factory.validateObject(underTest)) {
  851. destroy(underTest);
  852. destroyedByEvictorCount.incrementAndGet();
  853. } else {
  854. try {
  855. // 这里会将样本rollbackOnReturn、autoCommitOnReturn等
  856. factory.passivateObject(underTest);
  857. } catch (final Exception e) {
  858. destroy(underTest);
  859. destroyedByEvictorCount.incrementAndGet();
  860. }
  861. }
  862. }
  863. }
  864. // 如果状态为EVICTION或EVICTION_RETURN_TO_HEAD,修改为IDLE
  865. if (!underTest.endEvictionTest(idleObjects)) {
  866. //空
  867. }
  868. }
  869. }
  870. }
  871. }
  872. // 校验所有连接的未使用时间是否超过removeAbandonedTimeout
  873. final AbandonedConfig ac = this.abandonedConfig;
  874. if (ac != null && ac.getRemoveAbandonedOnMaintenance()) {
  875. removeAbandoned(ac);
  876. }
  877. }
  878. ```
  879. 以上已基本研究完数据源创建、连接对象获取和空闲资源回收器,后续有空再做补充。
  880. # 通过JNDI获取数据源对象
  881. ## 需求
  882. 本文测试使用`JNDI`获取`PerUserPoolDataSource`和`SharedPoolDataSource`对象,选择使用`tomcat 9.0.21`作容器。
  883. 如果之前没有接触过`JNDI`,并不会影响下面例子的理解,其实可以理解为像`spring`的`bean`配置和获取。
  884. 源码分析时已经讲到,除了我们熟知的`BasicDataSource`,`DBCP`还提供了通过`JDNI`获取数据源,如下表。
  885. | 类名 | 描述 |
  886. | ----------------------- | ------------------------------------------------------------ |
  887. | `InstanceKeyDataSource` | 用于支持`JDNI`环境的数据源,是以下两个类的父类 |
  888. | `PerUserPoolDataSource` | `InstanceKeyDataSource`的子类,针对每个用户会单独分配一个连接池,每个连接池可以设置不同属性。例如以下需求,相比user,`admin`可以创建更多地连接以保证 |
  889. | `SharedPoolDataSource` | `InstanceKeyDataSource`的子类,不同用户共享一个连接池 |
  890. ## 引入依赖
  891. 本文在前面例子的基础上增加以下依赖,因为是web项目,所以打包方式为`war`:
  892. ```xml
  893. <dependency>
  894. <groupId>javax.servlet</groupId>
  895. <artifactId>jstl</artifactId>
  896. <version>1.2</version>
  897. <scope>provided</scope>
  898. </dependency>
  899. <dependency>
  900. <groupId>javax.servlet</groupId>
  901. <artifactId>javax.servlet-api</artifactId>
  902. <version>3.1.0</version>
  903. <scope>provided</scope>
  904. </dependency>
  905. <dependency>
  906. <groupId>javax.servlet.jsp</groupId>
  907. <artifactId>javax.servlet.jsp-api</artifactId>
  908. <version>2.2.1</version>
  909. <scope>provided</scope>
  910. </dependency>
  911. ```
  912. ## 编写context.xml
  913. 在`webapp`文件下创建目录`META-INF`,并创建`context.xml`文件。这里面的每个`resource`节点都是我们配置的对象,类似于`spring`的`bean`节点。其中`bean/DriverAdapterCPDS`这个对象需要被另外两个使用到。
  914. ```xml
  915. <?xml version="1.0" encoding="UTF-8"?>
  916. <Context>
  917. <Resource
  918. name="bean/SharedPoolDataSourceFactory"
  919. auth="Container"
  920. type="org.apache.commons.dbcp2.datasources.SharedPoolDataSource"
  921. factory="org.apache.commons.dbcp2.datasources.SharedPoolDataSourceFactory"
  922. singleton="false"
  923. driverClassName="com.mysql.cj.jdbc.Driver"
  924. url="jdbc:mysql://localhost:3306/github_demo?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=true"
  925. username="root"
  926. password="root"
  927. maxTotal="8"
  928. maxIdle="10"
  929. dataSourceName="java:comp/env/bean/DriverAdapterCPDS"
  930. />
  931. <Resource
  932. name="bean/PerUserPoolDataSourceFactory"
  933. auth="Container"
  934. type="org.apache.commons.dbcp2.datasources.PerUserPoolDataSource"
  935. factory="org.apache.commons.dbcp2.datasources.PerUserPoolDataSourceFactory"
  936. singleton="false"
  937. driverClassName="com.mysql.cj.jdbc.Driver"
  938. url="jdbc:mysql://localhost:3306/github_demo?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=true"
  939. username="root"
  940. password="root"
  941. maxTotal="8"
  942. maxIdle="10"
  943. dataSourceName="java:comp/env/bean/DriverAdapterCPDS"
  944. />
  945. <Resource
  946. name="bean/DriverAdapterCPDS"
  947. auth="Container"
  948. type="org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS"
  949. factory="org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS"
  950. singleton="false"
  951. driverClassName="com.mysql.cj.jdbc.Driver"
  952. url="jdbc:mysql://localhost:3306/github_demo?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=true"
  953. userName="root"
  954. userPassword="root"
  955. maxIdle="10"
  956. />
  957. </Context>
  958. ```
  959. ## 编写web.xml
  960. 在`web-app`节点下配置资源引用,每个`resource-env-ref`指向了我们配置好的对象。
  961. ```xml
  962. <resource-env-ref>
  963. <description>Test DriverAdapterCPDS</description>
  964. <resource-env-ref-name>bean/DriverAdapterCPDS</resource-env-ref-name>
  965. <resource-env-ref-type>org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS</resource-env-ref-type>
  966. </resource-env-ref>
  967. <resource-env-ref>
  968. <description>Test SharedPoolDataSource</description>
  969. <resource-env-ref-name>bean/SharedPoolDataSourceFactory</resource-env-ref-name>
  970. <resource-env-ref-type>org.apache.commons.dbcp2.datasources.SharedPoolDataSource</resource-env-ref-type>
  971. </resource-env-ref>
  972. <resource-env-ref>
  973. <description>Test erUserPoolDataSource</description>
  974. <resource-env-ref-name>bean/erUserPoolDataSourceFactory</resource-env-ref-name>
  975. <resource-env-ref-type>org.apache.commons.dbcp2.datasources.erUserPoolDataSource</resource-env-ref-type>
  976. </resource-env-ref>
  977. ```
  978. ## 编写jsp
  979. 因为需要在`web`环境中使用,如果直接建类写个`main`方法测试,会一直报错的,目前没找到好的办法。这里就简单地使用`jsp`来测试吧(这是从tomcat官网参照的例子)。
  980. ```jsp
  981. <body>
  982. <%
  983. // 获得名称服务的上下文对象
  984. Context initCtx = new InitialContext();
  985. Context envCtx = (Context)initCtx.lookup("java:comp/env/");
  986. // 查找指定名字的对象
  987. DataSource ds = (DataSource)envCtx.lookup("bean/SharedPoolDataSourceFactory");
  988. DataSource ds2 = (DataSource)envCtx.lookup("bean/PerUserPoolDataSourceFactory");
  989. // 获取连接
  990. Connection conn = ds.getConnection("root","root");
  991. System.out.println("conn" + conn);
  992. Connection conn2 = ds2.getConnection("zzf","zzf");
  993. System.out.println("conn2" + conn2);
  994. // ... 使用连接操作数据库,以及释放资源 ...
  995. conn.close();
  996. conn2.close();
  997. %>
  998. </body>
  999. ```
  1000. ## 测试结果
  1001. 打包项目在`tomcat9`上运行,访问 http://localhost:8080/DBCP-demo/testInstanceKeyDataSource.jsp ,控制台打印如下内容:
  1002. ```
  1003. conn=1971654708, URL=jdbc:mysql://localhost:3306/github_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true, UserName=root@localhost, MySQL Connector/J
  1004. conn2=128868782, URL=jdbc:mysql://localhost:3306/github_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true, UserName=zzf@localhost, MySQL Connector/J
  1005. ```
  1006. # 使用DBCP测试两阶段提交
  1007. 前面源码分析已经讲到,以下类用于支持`JTA`事务。本文将介绍如何使用`DBCP`来实现`JTA`事务两阶段提交(当然,实际项目并不支持使用`2PC`,因为性能开销太大)。
  1008. | 类名 | 描述 |
  1009. | ------------------------ | ------------------------------------------------------------ |
  1010. | `BasicManagedDataSource` | `BasicDataSource`的子类,用于创建支持`XA`事务或`JTA`事务的连接 |
  1011. | `ManagedDataSource` | `PoolingDataSource`的子类,用于支持`XA`事务或`JTA`事务的连接。是`BasicManagedDataSource`中实际调用的数据源,可以说`BasicManagedDataSource`只是封装了`ManagedDataSource` |
  1012. ## 准备工作
  1013. 因为测试例子使用的是`mysql`,使用`XA`事务需要开启支持。注意,`mysql`只有`innoDB`引擎才支持(另外,`XA`事务和常规事务是互斥的,如果开启了`XA`事务,其他线程进来即使只读也是不行的)。
  1014. ```sql
  1015. SHOW VARIABLES LIKE '%xa%' -- 查看XA事务是否开启
  1016. SET innodb_support_xa = ON -- 开启XA事务
  1017. ```
  1018. 除了原来的`github_demo`数据库,我另外建了一个`test`数据库,简单地模拟两个数据库。
  1019. ## mysql的XA事务使用
  1020. 测试之前,这里简单回顾下直接使用`sql`操作`XA`事务的过程,将有助于对以下内容的理解:
  1021. ```sql
  1022. XA START 'my_test_xa'; -- 启动一个xid为my_test_xa的事务,并使之为active状态
  1023. UPDATE github_demo.demo_user SET deleted = 1 WHERE id = '1'; -- 事务中的语句
  1024. XA END 'my_test_xa'; -- 把事务置为idle状态
  1025. XA PREPARE 'my_test_xa'; -- 把事务置为prepare状态
  1026. XA COMMIT 'my_test_xa'; -- 提交事务
  1027. XA ROLLBACK 'my_test_xa'; -- 回滚事务
  1028. XA RECOVER; -- 查看处于prepare状态的事务列表
  1029. ```
  1030. ## 引入依赖
  1031. 在入门例子的基础上,增加以下依赖,本文采用第三方`atomikos`的实现。
  1032. ```xml
  1033. <!-- jta:用于测试DBCP对JTA事务的支持 -->
  1034. <dependency>
  1035. <groupId>javax.transaction</groupId>
  1036. <artifactId>jta</artifactId>
  1037. <version>1.1</version>
  1038. </dependency>
  1039. <dependency>
  1040. <groupId>com.atomikos</groupId>
  1041. <artifactId>transactions-jdbc</artifactId>
  1042. <version>3.9.3</version>
  1043. </dependency>
  1044. ```
  1045. ## 获取BasicManagedDataSource
  1046. 这里千万记得要设置`DefaultCatalog`,否则当前事务中注册不同资源管理器时,可能都会被当成同一个资源管理器而拒绝注册并报错,因为这个问题,花了我好长时间才解决。
  1047. ```java
  1048. public BasicManagedDataSource getBasicManagedDataSource(
  1049. TransactionManager transactionManager,
  1050. String url,
  1051. String username,
  1052. String password) {
  1053. BasicManagedDataSource basicManagedDataSource = new BasicManagedDataSource();
  1054. basicManagedDataSource.setTransactionManager(transactionManager);
  1055. basicManagedDataSource.setUrl(url);
  1056. basicManagedDataSource.setUsername(username);
  1057. basicManagedDataSource.setPassword(password);
  1058. basicManagedDataSource.setDefaultAutoCommit(false);
  1059. basicManagedDataSource.setXADataSource("com.mysql.cj.jdbc.MysqlXADataSource");
  1060. return basicManagedDataSource;
  1061. }
  1062. @Test
  1063. public void test01() throws Exception {
  1064. // 获得事务管理器
  1065. TransactionManager transactionManager = new UserTransactionManager();
  1066. // 获取第一个数据库的数据源
  1067. BasicManagedDataSource basicManagedDataSource1 = getBasicManagedDataSource(
  1068. transactionManager,
  1069. "jdbc:mysql://localhost:3306/github_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true",
  1070. "root",
  1071. "root");
  1072. // 注意,这一步非常重要
  1073. basicManagedDataSource1.setDefaultCatalog("github_demo");
  1074. // 获取第二个数据库的数据源
  1075. BasicManagedDataSource basicManagedDataSource2 = getBasicManagedDataSource(
  1076. transactionManager,
  1077. "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true",
  1078. "zzf",
  1079. "zzf");
  1080. // 注意,这一步非常重要
  1081. basicManagedDataSource1.setDefaultCatalog("test");
  1082. }
  1083. ```
  1084. ## 编写两阶段提交的代码
  1085. 通过运行代码可以发现,当数据库1和2的操作都成功,才会提交,只要其中一个数据库执行失败,两个操作都会回滚。
  1086. ```java
  1087. @Test
  1088. public void test01() throws Exception {
  1089. Connection connection1 = null;
  1090. Statement statement1 = null;
  1091. Connection connection2 = null;
  1092. Statement statement2 = null;
  1093. transactionManager.begin();
  1094. try {
  1095. // 获取连接并进行数据库操作,这里会将会将XAResource注册到当前线程的XA事务对象
  1096. /**
  1097. * XA START xid1;-- 启动一个事务,并使之为active状态
  1098. */
  1099. connection1 = basicManagedDataSource1.getConnection();
  1100. statement1 = connection1.createStatement();
  1101. /**
  1102. * update github_demo.demo_user set deleted = 1 where id = '1'; -- 事务中的语句
  1103. */
  1104. boolean result1 = statement1.execute("update github_demo.demo_user set deleted = 1 where id = '1'");
  1105. System.out.println(result1);
  1106. /**
  1107. * XA START xid2;-- 启动一个事务,并使之为active状态
  1108. */
  1109. connection2 = basicManagedDataSource2.getConnection();
  1110. statement2 = connection2.createStatement();
  1111. /**
  1112. * update test.demo_user set deleted = 1 where id = '1'; -- 事务中的语句
  1113. */
  1114. boolean result2 = statement2.execute("update test.demo_user set deleted = 1 where id = '1'");
  1115. System.out.println(result2);
  1116. /**
  1117. * 当这执行以下语句:
  1118. * XA END xid1; -- 把事务置为idle状态
  1119. * XA PREPARE xid1; -- 把事务置为prepare状态
  1120. * XA END xid2; -- 把事务置为idle状态
  1121. * XA PREPARE xid2; -- 把事务置为prepare状态
  1122. * XA COMMIT xid1; -- 提交事务
  1123. * XA COMMIT xid2; -- 提交事务
  1124. */
  1125. transactionManager.commit();
  1126. } catch(Exception e) {
  1127. e.printStackTrace();
  1128. } finally {
  1129. statement1.close();
  1130. statement2.close();
  1131. connection1.close();
  1132. connection2.close();
  1133. }
  1134. }
  1135. ```
  1136. > 相关源码请移步:https://github.com/ZhangZiSheng001/dbcp-demo
  1137. > 本文为原创文章,转载请附上原文出处链接:https://www.cnblogs.com/ZhangZiSheng001/p/12003922.html