【SpringBoot 】dynamic 动态数据源配置连接池(转)
前言在复杂的业务场景中我们经常需要使用多数据源来满足不同的数据访问需求。Dynamic Datasource 为我们提供了一种灵活切换不同数据源的解决方案。但是多数据源配置连接池 以及说明文档都是收费的。 本篇博文将详细介绍如何配置和优化 Dynamic Datasource 的连接池包括 Druid 和 HikariCP以及如何根据项目需求进行选择。连接池配置连接池是数据库连接管理的核心组件它可以显著提高数据库操作的性能。以下是使用 Dynamic Datasource 配置连接池的详细步骤选择连接池实现Druid阿里巴巴开源的数据库连接池监控功能强大配置灵活。HikariCP性能卓越是当前市面上最快的连接池之一。配置示例特此说明 如果配置配到了 spring.datasource.dynamic 下 druid 或者 hikari这表示这个配置将作用于 dynamic 的所有数据源在 application.yml 中配置连接池参数以下为 Druid 和 HikariCP 的配置示例。spring: datasource: dynamic: # 全局配置的hikari 或druid # hikari 官方文档 hikari: # 最小空闲数量 min-idle: 10 # 最小空闲数量 minimumIdle: # 连接池最大数量 max-pool-size: 100 # 连接池最大数量 maximum-pool-size: # 连接超时时间 connectionTimeout: # 校验超时时间 validationTimeout: # 空闲超时时间 idleTimeout: # 此属性控制在记录指示可能的连接泄漏的消息之前连接可以离开池的时间量。值为0表示关闭泄漏检测。启用泄漏检测的最低可接受值是2000(2秒)。默认值:0 leakDetectionThreshold: # 此属性控制池中连接的最大生存期 值为0表示没有最大生存期(无限生存期)当然取决于idleTimeout设置。最小允许值为30000ms(30秒)。默认值:1800000(30分钟) maxLifetime: # 初始化失败超时时间 即 到了指定时间还没初始化完成就算失败 initializationFailTimeout: # 连接初始化SQL connectionInitSql: # 连接查询测试SQL connectionTestQuery: # 数据源类名 dataSourceClassName: com.zaxxer.hikari.HikariDataSource dataSourceJndiName: # 事务隔离级别名称 transactionIsolationName: # 自动提交 isAutoCommit: # 是否只读 isReadOnly: # 是否隔离内部查询 isIsolateInternalQueries: # 是否注册 mbean isRegisterMbeans: # 是否允许pool 挂起 isAllowPoolSuspension: # 存活时间 keepaliveTime: druid: # 官方文档: https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8 # 初始化数量 初始化时建立物理连接的个数。初始化发生在显示调用init方法或者第一次getConnection时 initialSize: 50 # 最大存活数量 maxActive: 50 # 最小空闲数量最小连接池数量 minIdle: 20 # 配置获取连接等待超时的时间 maxWait: # 配置间隔多久才进行一次检测检测需要关闭的空闲连接单位是毫秒 timeBetweenEvictionRunsMillis: # 配置间隔多久才进行日志统计单位是毫秒 timeBetweenLogStatsMillis: # 统计SQL最大数量 statSqlMaxSize: # 配置一个连接在池中最小生存的时间单位是毫秒 minEvictableIdleTimeMillis: # 配置一个连接在池中最大生存的时间单位是毫秒 maxEvictableIdleTimeMillis: # 是否自动提交 defaultAutoCommit: # 是否只读 defaultReadOnly: # 默认事务隔离级别 defaultTransactionIsolation: # 连接空闲测试 testWhileIdle: # 当获取连接测试 testOnBorrow: # 当归还连接测试 testOnReturn: # 验证查询SQL validationQuery: # 验证查询超时时间 validationQueryTimeout: # 使用全局数据源统计 useGlobalDataSourceStat: # 异步初始化 asyncInit: # 配置监控统计拦截的filters filters: stat clearFiltersEnable: # 重置统计开关 resetStatEnable: notFullTimeoutRetryCount: # 最大等待线程数量 maxWaitThreadCount: # 快速失败 failFast: phyTimeoutMillis: # 保持连接开关 连接池中的minIdle数量以内的连接空闲时间超过minEvictableIdleTimeMillis则会执行keepAlive操作。 keepAlive: # ps pool开关 poolPreparedStatements: initVariants: initGlobalVariants: # 使用非公平锁 useUnfairLock: # socket读取超时 kill killWhenSocketReadTimeout: # 每个连接 最大ps 池数量 maxPoolPreparedStatementPerConnectionSize: # 共享ps sharePreparedStatements: # 连接错误重试次数 connectionErrorRetryAttempts: # 配置获取锁失败多少次 中断 breakAfterAcquireFailure: removeAbandoned: removeAbandonedTimeoutMillis: # 查询超时时间 queryTimeout: # 事务查询超时时间 transactionQueryTimeout: # 连接超时时间 connectTimeout: # socket 连接超时时间 socketTimeout: datasource: ds1: url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver #type: com.zaxxer.hikari.HikariDataSource type: com.alibaba.druid.pool.DruidDataSource #注意hikari和druid选择一个使用 # hikari 官方文档 hikari: ## 与上述全局 hikari 配置相同 druid: # 与上述全局 druid 配置相同 ds2: url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver配置说明HikariCPmin-idle连接池中最小空闲连接数量。max-pool-size连接池最大连接数量。connection-timeout连接超时时间。validation-timeout验证超时时间。idle-timeout空闲超时时间。leak-detection-threshold连接泄露检测阈值。max-lifetime连接最大存活时间。Druidinitial-size初始化时建立的连接数量。max-active连接池最大连接数量。min-idle连接池中的最小空闲连接数量。max-wait获取连接最大等待时间。time-between-eviction-runs-millis检测连接间隔时间。min-evictable-idle-time-millis连接最小空闲时间。validation-query检测连接有效性的SQL。filters监控和防御插件。文档资料官方文档 点我最佳实践性能调优根据应用的负载和数据库性能合理配置连接池大小。启用连接泄露检测及时发现并修复连接泄露问题。实时监控使用监控工具如 Prometheus、Zabbix监控数据库连接池状态包括活跃连接数、等待连接数、连接池利用率等。性能基准测试使用工具如 JMeter、LoadRunner模拟数据库操作测试连接池的性能表现。慢查询日志分析配置并分析慢查询日志找出性能瓶颈并进行优化。安全最佳实践密码加密对数据库连接使用的密码进行加密可以使用第三方库如 Jasypt来实现。访问控制严格控制数据库访问权限遵循最小权限原则。定期安全审计定期进行数据库安全审计检查潜在的安全风险。监控和日志启用连接池监控实时监控数据库连接状态。配置慢查询日志及时发现并优化慢查询动态数据资源的原理要使用就引入这jar就行dependency groupIdcom.baomidou/groupId artifactIddynamic-datasource-spring-boot-starter/artifactId /dependency介绍如果系统里面配置了多个数据源的情况就涉及到到底当前service的方法 使用哪个数据源的问题基本逻辑就是 动态属于定制一个自己的AOP代理拦截servcie方法的调用在调用之前会从当前被调用的方法和类上面获取 DSxxx 这个配置信息然后设置到当前线程上下文中。动态数据源的自动装配org.springframework.boot.autoconfigure.EnableAutoConfiguration\ com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfigurationConfiguration EnableConfigurationProperties({DynamicDataSourceProperties.class}) AutoConfigureBefore( value {DataSourceAutoConfiguration.class}, name {com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure} ) Import({DruidDynamicDataSourceConfiguration.class, DynamicDataSourceCreatorAutoConfiguration.class, DynamicDataSourceAopConfiguration.class, DynamicDataSourceAssistConfiguration.class}) ConditionalOnProperty( prefix spring.datasource.dynamic, name {enabled}, havingValue true, matchIfMissing true ) public class DynamicDataSourceAutoConfiguration implements InitializingBean { private static final Logger log LoggerFactory.getLogger(DynamicDataSourceAutoConfiguration.class); private final DynamicDataSourceProperties properties; private final ListDynamicDataSourcePropertiesCustomizer dataSourcePropertiesCustomizers; public DynamicDataSourceAutoConfiguration(DynamicDataSourceProperties properties, ObjectProviderListDynamicDataSourcePropertiesCustomizer dataSourcePropertiesCustomizers) { this.properties properties; this.dataSourcePropertiesCustomizers (List)dataSourcePropertiesCustomizers.getIfAvailable(); } ///返回一个 动态数据源 DynamicRoutingDataSource //这个数据源 里面有一个MapString,DataSource // 这样就可以通过key获取对应的数据源 Bean ConditionalOnMissingBean public DataSource dataSource(ListDynamicDataSourceProvider providers) { DynamicRoutingDataSource dataSource new DynamicRoutingDataSource(providers); dataSource.setPrimary(this.properties.getPrimary()); dataSource.setStrict(this.properties.getStrict()); dataSource.setStrategy(this.properties.getStrategy()); dataSource.setP6spy(this.properties.getP6spy()); dataSource.setSeata(this.properties.getSeata()); dataSource.setGraceDestroy(this.properties.getGraceDestroy()); return dataSource; } public void afterPropertiesSet() { if (!CollectionUtils.isEmpty(this.dataSourcePropertiesCustomizers)) { Iterator var1 this.dataSourcePropertiesCustomizers.iterator(); while(var1.hasNext()) { DynamicDataSourcePropertiesCustomizer customizer (DynamicDataSourcePropertiesCustomizer)var1.next(); customizer.customize(this.properties); } } } }核心代码逻辑public class DynamicDataSourceAnnotationInterceptor implements MethodInterceptor 这个类的代码。 Service层面代码调用之前的拦截器public Object invoke(MethodInvocation invocation) throws Throwable { ///invocation这个封装的就是 当前被到用的方法的信息 可以从method获取到class注解 //当然DS注解也可以放在方法层面。 String dsKey this.determineDatasourceKey(invocation); // DynamicDataSourceContextHolder.push(dsKey); Object var3; try { //调用service具体的方法 var3 invocation.proceed(); } finally { //销毁上下文的信息 DynamicDataSourceContextHolder.poll(); } return var3; } /////////////////方法上的DS配置 优先基本高于class级别的 Service DS(user) public class UserServiceImpl implements UserService { Autowired private UserMapper userMapper; Override DS(order) public ListUser findAll() { return userMapper.selectAll(); } }Mapper层面怎么获取数据源查询时不会在service层面开启事务代码分析过程类信息: public class SimpleExecutor extends BaseExecutor public E ListE doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { Statement stmt null; try { Configuration configuration ms.getConfiguration(); StatementHandler handler configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); ///获取具体的jdbc 的操作Statement。这个就要确定最后的Connection了就是确定具体是那个数据库了 stmt prepareStatement(handler, ms.getStatementLog()); return handler.query(stmt, resultHandler); } finally { closeStatement(stmt); } } //上面的prepareStatement方法 private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException { Statement stmt; //这里就是处理jdbc链接获取的时候 Connection connection getConnection(statementLog); stmt handler.prepare(connection, transaction.getTimeout()); handler.parameterize(stmt); return stmt; } //父类的方法 protected Connection getConnection(Log statementLog) throws SQLException { //通过mybaits中的 Transaction transaction; 事务管理器获取链接 //因为事务管理器是 要管理链接的事务相关的内容 所以从这里获取也是合理的 Connection connection transaction.getConnection(); if (statementLog.isDebugEnabled()) { return ConnectionLogger.newInstance(connection, statementLog, queryStack); } return connection; } //上面的事务管理器SpringManagedTransaction是 mybatis为了结合spring所的一个 package org.mybatis.spring.transaction public class SpringManagedTransaction implements Transaction ///transaction.getConnection(); Override public Connection getConnection() throws SQLException { if (this.connection null) { openConnection(); } return this.connection; } ///SpringManagedTransaction类的 private void openConnection() throws SQLException { ///this.dataSource 这个对象 就是DynamicRoutingDataSource 自动装配创建的动态数据源 // DataSourceUtils 会从线程上下文获取 在service层面注入的key 获取具体的 DynamicRoutingDataSource中的Map中的对应的数据源 this.connection DataSourceUtils.getConnection(this.dataSource); this.autoCommit this.connection.getAutoCommit(); this.isConnectionTransactional DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource); LOGGER.debug(() - JDBC Connection [ this.connection ] will (this.isConnectionTransactional ? : not ) be managed by Spring); } /////DataSourceUtils这类的方法 public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException { try { return doGetConnection(dataSource); } catch (SQLException var2) { SQLException ex var2; throw new CannotGetJdbcConnectionException(Failed to obtain JDBC Connection, ex); } catch (IllegalStateException var3) { IllegalStateException ex var3; throw new CannotGetJdbcConnectionException(Failed to obtain JDBC Connection, ex); } } //////DataSourceUtils这类的方法 private static Connection fetchConnection(DataSource dataSource) throws SQLException { Connection con dataSource.getConnection(); if (con null) { throw new IllegalStateException(DataSource returned null from getConnection(): dataSource); } else { return con; } } //package com.baomidou.dynamic.datasource.ds //public abstract class AbstractRoutingDataSource extends AbstractDataSource public Connection getConnection() throws SQLException { //xid是 一个用于获取当前全局事务唯一标识XID的方法 用于分布式事务的 String xid TransactionContext.getXID(); if (DsStrUtils.isEmpty(xid)) { //这里 return this.determineDataSource().getConnection(); } else { String ds DynamicDataSourceContextHolder.peek(); //如果service上没注解 那就取主 数据源 ds DsStrUtils.isEmpty(ds) ? this.getPrimary() : ds; ConnectionProxy connection ConnectionFactory.getConnection(xid, ds); return (Connection)(connection null ? this.getConnectionProxy(xid, ds, this.determineDataSource().getConnection()) : connection); } } /// DynamicRoutingDataSource 要回到了动态数据源了中 public DataSource determineDataSource() { //这里会弹出DynamicDataSourceContextHolder.peek(); 之前上下文保存的key //然后获取对应的数据源了。 String dsKey DynamicDataSourceContextHolder.peek(); return this.getDataSource(dsKey); }更新操作service开启了事务配置了EnableTransactionManagementTransactional(rollbackFor Exception.class) public ListUser findAll() { return userMapper.selectAll(); }开启了事务配置那么service方法拦截器链中要多另一个事务连接器。具体代码 CglibAopProxy service首先代用这个动态代理类的public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { Object oldProxy null; boolean setProxyContext false; Object target null; TargetSource targetSource this.advised.getTargetSource(); try { if (this.advised.exposeProxy) { // Make invocation available if necessary. oldProxy AopContext.setCurrentProxy(proxy); setProxyContext true; } // Get as late as possible to minimize the time we own the target, in case it comes from a pool... target targetSource.getTarget(); Class? targetClass (target ! null ? target.getClass() : null); ///每次定义一个aop拦截 就会在链中多一个 拦截器 /// ListObject chain this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); Object retVal; // Check whether we only have one InvokerInterceptor: that is, // no real advice, but just reflective invocation of the target. if (chain.isEmpty() CglibMethodInvocation.isMethodProxyCompatible(method)) { // We can skip creating a MethodInvocation: just invoke the target directly. // Note that the final invoker must be an InvokerInterceptor, so we know // it does nothing but a reflective operation on the target, and no hot // swapping or fancy proxying. Object[] argsToUse AopProxyUtils.adaptArgumentsIfNecessary(method, args); retVal invokeMethod(target, method, argsToUse, methodProxy); } else { // We need to create a method invocation... retVal new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed(); } retVal processReturnType(proxy, target, method, retVal); return retVal; } finally { if (target ! null !targetSource.isStatic()) { targetSource.releaseTarget(target); } if (setProxyContext) { // Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } }调试结果动态数据源的方法的代码上面分析过就是在上下文 放一个key .现在我们分析:TransactionInterceptor拦截器public Object invoke(final MethodInvocation invocation) throws Throwable { Class? targetClass invocation.getThis() ! null ? AopUtils.getTargetClass(invocation.getThis()) : null; ///基于事务的调用 就是要先开启一个事务那么就要先获取数据源的链接 然后 //调用setAutoCommit(false) 那么怎么获取想要的链接的呢 //上面的查询 是在Mapper层才开始获取链接的而这是要提前在service方法调用之前就获取 // return this.invokeWithinTransaction(invocation.getMethod(), targetClass, new TransactionAspectSupport.CoroutinesInvocationCallback() { ///调用会 走到这里 invocation 就是被代理的方法调用的封装。 public Object proceedWithInvocation() throws Throwable { return invocation.proceed(); } public Object getTarget() { return invocation.getThis(); } public Object[] getArguments() { return invocation.getArguments(); } }); } /////org.springframework.aop.framework.ReflectiveMethodInvocation public Object proceed() throws Throwable { // We start with an index of -1 and increment early. if (this.currentInterceptorIndex this.interceptorsAndDynamicMethodMatchers.size() - 1) { return invokeJoinpoint(); } Object interceptorOrInterceptionAdvice this.interceptorsAndDynamicMethodMatchers.get(this.currentInterceptorIndex); if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) { // Evaluate dynamic method matcher here: static part will already have // been evaluated and found to match. InterceptorAndDynamicMethodMatcher dm (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice; Class? targetClass (this.targetClass ! null ? this.targetClass : this.method.getDeclaringClass()); if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) { return dm.interceptor.invoke(this); } else { // Dynamic matching failed. // Skip this interceptor and invoke the next in the chain. return proceed(); } } else { // Its an interceptor, so we just invoke it: The pointcut will have // been evaluated statically before this object was constructed. ///走到这 这个interceptorOrInterceptionAdvice是事务拦截器 ///org.springframework.transaction.interceptor.TransactionInterceptor return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); } } ///org.springframework.transaction.interceptor.TransactionInterceptor ///调用他父类方法 TransactionAspectSupport.invokeWithinTransaction protected Object invokeWithinTransaction(Method method, Nullable Class? targetClass, final InvocationCallback invocation) throws Throwable { //获取事务的属性 比如回滚异常 隔离级别 传播方式等 TransactionAttributeSource tas this.getTransactionAttributeSource(); TransactionAttribute txAttr tas ! null ? tas.getTransactionAttribute(method, targetClass) : null; /// TransactionManager tm this.determineTransactionManager(txAttr); if (this.reactiveAdapterRegistry ! null tm instanceof ReactiveTransactionManager) { boolean isSuspendingFunction KotlinDetector.isSuspendingFunction(method); boolean hasSuspendingFlowReturnType isSuspendingFunction kotlinx.coroutines.flow.Flow.equals((new MethodParameter(method, -1)).getParameterType().getName()); if (isSuspendingFunction !(invocation instanceof CoroutinesInvocationCallback)) { throw new IllegalStateException(Coroutines invocation not supported: method); } else { CoroutinesInvocationCallback corInv isSuspendingFunction ? (CoroutinesInvocationCallback)invocation : null; ReactiveTransactionSupport txSupport (ReactiveTransactionSupport)this.transactionSupportCache.computeIfAbsent(method, (key) - { Class? reactiveType isSuspendingFunction ? (hasSuspendingFlowReturnType ? Flux.class : Mono.class) : method.getReturnType(); ReactiveAdapter adapter this.reactiveAdapterRegistry.getAdapter(reactiveType); if (adapter null) { throw new IllegalStateException(Cannot apply reactive transaction to non-reactive return type: method.getReturnType()); } else { return new ReactiveTransactionSupport(adapter); } }); InvocationCallback callback invocation; if (corInv ! null) { callback () - { return CoroutinesUtils.invokeSuspendingFunction(method, corInv.getTarget(), corInv.getArguments()); }; } Object result txSupport.invokeWithinTransaction(method, targetClass, callback, txAttr, (ReactiveTransactionManager)tm); if (corInv ! null) { Publisher? pr (Publisher)result; return hasSuspendingFlowReturnType ? TransactionAspectSupport.KotlinDelegate.asFlow(pr) : TransactionAspectSupport.KotlinDelegate.awaitSingleOrNull(pr, corInv.getContinuation()); } else { return result; } } } else { PlatformTransactionManager ptm this.asPlatformTransactionManager(tm); String joinpointIdentification this.methodIdentification(method, targetClass, txAttr); Throwable ex2; if (txAttr ! null ptm instanceof CallbackPreferringPlatformTransactionManager) { ThrowableHolder throwableHolder new ThrowableHolder(); Object result; try { result ((CallbackPreferringPlatformTransactionManager)ptm).execute(txAttr, (statusx) - { TransactionInfo txInfo this.prepareTransactionInfo(ptm, txAttr, joinpointIdentification, statusx); Object var9; try { Object retVal invocation.proceedWithInvocation(); if (retVal ! null vavrPresent TransactionAspectSupport.VavrDelegate.isVavrTry(retVal)) { retVal TransactionAspectSupport.VavrDelegate.evaluateTryFailure(retVal, txAttr, statusx); } var9 retVal; return var9; } catch (Throwable var13) { Throwable ex var13; if (txAttr.rollbackOn(ex)) { if (ex instanceof RuntimeException) { throw (RuntimeException)ex; } throw new ThrowableHolderException(ex); } throwableHolder.throwable ex; var9 null; } finally { this.cleanupTransactionInfo(txInfo); } return var9; }); } catch (ThrowableHolderException var22) { ThrowableHolderException ex var22; throw ex.getCause(); } catch (TransactionSystemException var23) { TransactionSystemException ex2 var23; if (throwableHolder.throwable ! null) { this.logger.error(Application exception overridden by commit exception, throwableHolder.throwable); ex2.initApplicationException(throwableHolder.throwable); } throw ex2; } catch (Throwable var24) { ex2 var24; if (throwableHolder.throwable ! null) { this.logger.error(Application exception overridden by commit exception, throwableHolder.throwable); } throw ex2; } if (throwableHolder.throwable ! null) { throw throwableHolder.throwable; } else { return result; } } else { ///最后会在这个方法 里面 获取事务管理器 然后获取链接 设置事务 //也是通过动态数据源拦截器 设置的key 来获取对应的数据源 然后获取链接的。 TransactionInfo txInfo this.createTransactionIfNecessary(ptm, txAttr, joinpointIdentification); Object retVal; try { retVal invocation.proceedWithInvocation(); } catch (Throwable var20) { ex2 var20; this.completeTransactionAfterThrowing(txInfo, ex2); throw ex2; } finally { this.cleanupTransactionInfo(txInfo); } if (retVal ! null vavrPresent TransactionAspectSupport.VavrDelegate.isVavrTry(retVal)) { TransactionStatus status txInfo.getTransactionStatus(); if (status ! null txAttr ! null) { retVal TransactionAspectSupport.VavrDelegate.evaluateTryFailure(retVal, txAttr, status); } } this.commitTransactionAfterReturning(txInfo); return retVal; } } } ////核心方法 在DataSourceTransactionManager protected void doBegin(Object transaction, TransactionDefinition definition) { DataSourceTransactionObject txObject (DataSourceTransactionObject)transaction; Connection con null; try { if (!txObject.hasConnectionHolder() || txObject.getConnectionHolder().isSynchronizedWithTransaction()) { ///这里是获取具体的链接 this.obtainDataSource()获取的是动态数据源对象 //动态数据源类的getConnection方法就会根据上下文中的key获取对应的数据源 Connection newCon this.obtainDataSource().getConnection(); if (this.logger.isDebugEnabled()) { this.logger.debug(Acquired Connection [ newCon ] for JDBC transaction); } ///然后也会把获取到的链接设置到事务上下文因为的Mapper应该还是要用这个链接 ///操作数据库的 txObject.setConnectionHolder(new ConnectionHolder(newCon), true); } txObject.getConnectionHolder().setSynchronizedWithTransaction(true); con txObject.getConnectionHolder().getConnection(); Integer previousIsolationLevel DataSourceUtils.prepareConnectionForTransaction(con, definition); txObject.setPreviousIsolationLevel(previousIsolationLevel); txObject.setReadOnly(definition.isReadOnly()); if (con.getAutoCommit()) { txObject.setMustRestoreAutoCommit(true); if (this.logger.isDebugEnabled()) { this.logger.debug(Switching JDBC Connection [ con ] to manual commit); } con.setAutoCommit(false); } this.prepareTransactionalConnection(con, definition); txObject.getConnectionHolder().setTransactionActive(true); int timeout this.determineTimeout(definition); if (timeout ! -1) { txObject.getConnectionHolder().setTimeoutInSeconds(timeout); } if (txObject.isNewConnectionHolder()) { TransactionSynchronizationManager.bindResource(this.obtainDataSource(), txObject.getConnectionHolder()); } } catch (Throwable var7) { Throwable ex var7; if (txObject.isNewConnectionHolder()) { DataSourceUtils.releaseConnection(con, this.obtainDataSource()); txObject.setConnectionHolder((ConnectionHolder)null, false); } throw new CannotCreateTransactionException(Could not open JDBC Connection for transaction, ex); } } ////////////////////TransactionAspectSupport(也就是TransactionInterceptor的父类) protected TransactionInfo createTransactionIfNecessary(Nullable PlatformTransactionManager tm, Nullable TransactionAttribute txAttr, final String joinpointIdentification) { if (txAttr ! null ((TransactionAttribute)txAttr).getName() null) { txAttr new DelegatingTransactionAttribute((TransactionAttribute)txAttr) { public String getName() { return joinpointIdentification; } }; } TransactionStatus status null; if (txAttr ! null) { if (tm ! null) { ///TransactionStatus 这个对象中封装了这个tm.getTransaction方法获取的事务信息 //已经当前事务使用的Connection 因为后面要用到这个链接操作 status tm.getTransaction((TransactionDefinition)txAttr); } else if (this.logger.isDebugEnabled()) { this.logger.debug(Skipping transactional joinpoint [ joinpointIdentification ] because no transaction manager has been configured); } } ///下面就要出来把 这个status存放到当前线程上下文中去 方便后面获取事务 然后获取链接 return this.prepareTransactionInfo(tm, (TransactionAttribute)txAttr, joinpointIdentification, status); } ////////////// protected TransactionInfo prepareTransactionInfo(Nullable PlatformTransactionManager tm, Nullable TransactionAttribute txAttr, String joinpointIdentification, Nullable TransactionStatus status) { TransactionInfo txInfo new TransactionInfo(tm, txAttr, joinpointIdentification); if (txAttr ! null) { if (this.logger.isTraceEnabled()) { this.logger.trace(Getting transaction for [ txInfo.getJoinpointIdentification() ]); } txInfo.newTransactionStatus(status); } else if (this.logger.isTraceEnabled()) { this.logger.trace(No need to create transaction for [ joinpointIdentification ]: This method is not transactional.); } ///把事务信息 绑定到线程中去 txInfo.bindToThread(); return txInfo; }上面事务拦截器 提前获取了对应的key的链接和事务对象了然后把事务对象包含了链接信息存放到当前线程上下文了下面就要分析 Mapper具体是怎么获取链接操作数据库的是否和上面非事务拦截器的方式一样呢? 还有如果 在这个service中的方法除了调用 本数据库 还要调用另外一个数据库的接口呢? 比如 MapperA 使用user库 MapperB使用Order库但是service层只能配置一个数据源 比如配置了user那么在service 方法调用mapperb方法时 是否有问题按道理是有问题的因为MapperB也会 从线程上下文中获取 链接和事务信息 但是这个事务对象要是封装了 第一个key(user) 的链接。继续跟踪代码分析调用要进入类 TransactionInterceptor public Object invoke(final MethodInvocation invocation) throws Throwable { Class? targetClass invocation.getThis() ! null ? AopUtils.getTargetClass(invocation.getThis()) : null; return this.invokeWithinTransaction(invocation.getMethod(), targetClass, new TransactionAspectSupport.CoroutinesInvocationCallback() { Nullable public Object proceedWithInvocation() throws Throwable { //具体的service方法调用了 return invocation.proceed(); } public Object getTarget() { return invocation.getThis(); } public Object[] getArguments() { return invocation.getArguments(); } }); } ////////和上面的非事务 查询 数据库方法一样都会调用到 /// package org.springframework.jdbc.datasource;DataSourceUtils public static Connection doGetConnection(DataSource dataSource) throws SQLException { Assert.notNull(dataSource, No DataSource specified); ///数据源就是动态数据源对象 从TransactionSynchronizationManager.getResource(dataSource);获取上面存放的事务对象 ///里面就是一个Map 然后key是具体的数据源对象这里是动态数据源对象然后获取里面的事务封装对象 获取的信息 看下图 ConnectionHolder conHolder (ConnectionHolder)TransactionSynchronizationManager.getResource(dataSource); if (conHolder null || !conHolder.hasConnection() !conHolder.isSynchronizedWithTransaction()) { logger.debug(Fetching JDBC Connection from DataSource); Connection con fetchConnection(dataSource); if (TransactionSynchronizationManager.isSynchronizationActive()) { try { ConnectionHolder holderToUse conHolder; if (holderToUse null) { holderToUse new ConnectionHolder(con); } else { holderToUse.setConnection(con); } holderToUse.requested(); TransactionSynchronizationManager.registerSynchronization(new ConnectionSynchronization(holderToUse, dataSource)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse ! conHolder) { TransactionSynchronizationManager.bindResource(dataSource, holderToUse); } } catch (RuntimeException var4) { RuntimeException ex var4; releaseConnection(con, dataSource); throw ex; } } return con; } else { //由于上面已经存放了ConnectionHolder 所以就跳到这里不用执行上的Connection con fetchConnection(dataSource); 根据key获取数据源信息了。 但是如果另外一个数据源的mappper 就会有问题了以为他要用另外一个数据库的链接才行。 conHolder.requested(); if (!conHolder.hasConnection()) { logger.debug(Fetching resumed JDBC Connection from DataSource); conHolder.setConnection(fetchConnection(dataSource)); } return conHolder.getConnection(); } }
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2453471.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!