当前位置: 首页 > article >正文

【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(); } }

相关文章:

【SpringBoot 】dynamic 动态数据源配置连接池(转)

前言 在复杂的业务场景中,我们经常需要使用多数据源来满足不同的数据访问需求。Dynamic Datasource 为我们提供了一种灵活切换不同数据源的解决方案。但是多数据源配置连接池 以及说明文档都是收费的。 本篇博文将详细介绍如何配置和优化 Dynamic Datasource 的连接…...

SecGPT-14B实战手册:Chainlit中集成Markdown渲染与代码块语法高亮

SecGPT-14B实战手册:Chainlit中集成Markdown渲染与代码块语法高亮 1. SecGPT-14B简介 SecGPT是由云起无垠推出的开源大语言模型,专门针对网络安全领域优化。该模型基于先进的自然语言处理技术,能够理解和生成与网络安全相关的专业内容。 S…...

YOLOv5实战:如何用Inner-IoU提升小目标检测效果(附完整代码)

YOLOv5实战:用Inner-IoU解决小目标检测痛点的工程指南 无人机镜头下的蚂蚁、CT扫描中的微小结节、卫星图像里的车辆——当目标尺寸小于3232像素时,传统检测器的性能往往会断崖式下跌。我们团队在医疗影像分析项目中就曾遇到这样的困境:常规Io…...

Cesium使用

Cesium官网:https://cesiumjs.org 官方API文档:https://cesium.com/learn/ion-sdk/ref-doc 中文API文档:https://cesium.xin/cesium/cn/Documentation1.95        https://cesium.xin Cesium中文社区:http://cesiumcn.org …...

Qwen2.5-72B-GPTQ-Int4保姆级教程:log排查技巧+Chainlit响应延迟优化

Qwen2.5-72B-GPTQ-Int4保姆级教程:log排查技巧Chainlit响应延迟优化 1. 模型简介与部署准备 Qwen2.5-72B-Instruct-GPTQ-Int4是通义千问大模型系列的最新版本,在知识量、编程能力和数学能力方面有显著提升。这个72.7B参数的模型经过GPTQ 4-bit量化&…...

Mac能够连接校园网,但是无法上网

Mac电脑能够正常连接校园网,但是无法上网解决步骤:打开系统设置,网络,WI-FI,DNS把现有的删掉重置它。原因分析:应该是在使用代理时、访问什么网站被自动篡改了 DNS 设置,导致连接的 DNS 无法解析…...

终极指南:GoldHEN Cheats Manager - PlayStation 4游戏作弊代码完整管理方案

终极指南:GoldHEN Cheats Manager - PlayStation 4游戏作弊代码完整管理方案 【免费下载链接】GoldHEN_Cheat_Manager GoldHEN Cheats Manager 项目地址: https://gitcode.com/gh_mirrors/go/GoldHEN_Cheat_Manager GoldHEN Cheats Manager 是一款专为PlaySt…...

LumiPixel优化升级:如何利用Z-Image模型生成更细腻的像素人像

LumiPixel优化升级:如何利用Z-Image模型生成更细腻的像素人像 1. 引言:像素艺术的复兴与挑战 像素艺术作为一种独特的数字艺术形式,近年来在游戏、NFT和数字设计领域迎来复兴。然而传统像素创作面临两大核心挑战: 细节表现力不…...

AutoDock Vina特殊金属元素对接技术指南:从问题诊断到方案落地

AutoDock Vina特殊金属元素对接技术指南:从问题诊断到方案落地 【免费下载链接】AutoDock-Vina AutoDock Vina 项目地址: https://gitcode.com/gh_mirrors/au/AutoDock-Vina 问题溯源:金属元素对接的技术瓶颈 在分子对接实践中,科研人…...

Phi-4-Reasoning-Vision开源模型:Phi-4-reasoning-vision-15B双卡推理镜像详解

Phi-4-Reasoning-Vision开源模型:Phi-4-reasoning-vision-15B双卡推理镜像详解 1. 项目概述 Phi-4-Reasoning-Vision是基于微软Phi-4-reasoning-vision-15B多模态大模型开发的高性能推理工具,专为双卡RTX 4090环境优化设计。这个工具严格遵循官方SYSTE…...

探索Tabler Icons 3.40.0:新增6000+高质量SVG图标的终极指南

探索Tabler Icons 3.40.0:新增6000高质量SVG图标的终极指南 【免费下载链接】tabler-icons A set of over 4800 free MIT-licensed high-quality SVG icons for you to use in your web projects. 项目地址: https://gitcode.com/GitHub_Trending/ta/tabler-icons…...

面向对象高级三:内部类 枚举 泛型 java.lang包下常用API

一.内部类1.内部类概述 2.成员内部类(实例内部类)(1)成员内部类可以定义类的一切成员(2)当创建对象时不能直接给内部类创建对象而要先创建外部类的对象 然后new成员内部类的对象(3)在…...

解码 DINO 核心:三大创新如何重塑端到端目标检测

1. 从DETR到DINO:目标检测的范式革命 记得我第一次用Faster R-CNN做目标检测时,光是调整锚框尺寸就花了整整三天。这种传统检测方法就像用老式打字机写代码——每个环节都需要手工微调。直到2020年DETR横空出世,才让我意识到目标检测还能这么…...

Wan2.2-T2V-A5B提示词怎么写?新手快速出效果的实用指南

Wan2.2-T2V-A5B提示词怎么写?新手快速出效果的实用指南 1. 认识Wan2.2-T2V-A5B视频生成模型 Wan2.2-T2V-A5B是一款由通义万相开源的轻量级文本到视频生成模型,拥有50亿参数规模。虽然它生成的视频分辨率是480P,但在时序连贯性和运动推理能力…...

NaViL-9B多模态模型5分钟快速部署:图文问答零基础入门教程

NaViL-9B多模态模型5分钟快速部署:图文问答零基础入门教程 1. 认识NaViL-9B多模态模型 NaViL-9B是上海人工智能实验室推出的原生多模态大语言模型,它不仅能像传统语言模型一样处理纯文本问答,还具备强大的图片理解能力。这意味着你可以上传…...

如何将Uvicorn部署到Azure Functions Premium Plan:完整指南

如何将Uvicorn部署到Azure Functions Premium Plan:完整指南 【免费下载链接】uvicorn An ASGI web server, for Python. 🦄 项目地址: https://gitcode.com/GitHub_Trending/uv/uvicorn Uvicorn是Python生态中备受推崇的ASGI Web服务器&#xff…...

手把手教你用YOLOv5训练自己的交通标志数据集(从LabelImg标注到模型部署)

从零构建YOLOv5交通标志检测器的实战指南 在自动驾驶和智能交通系统快速发展的今天,准确识别道路标志已成为计算机视觉领域的重要应用场景。不同于传统图像处理方法,基于深度学习的目标检测技术能够适应复杂环境变化,而YOLOv5以其卓越的速度-…...

Project Sistine核心代码剖析:从图像分割到鼠标事件模拟

Project Sistine核心代码剖析:从图像分割到鼠标事件模拟 【免费下载链接】sistine Turn a MacBook into a Touchscreen with $1 of Hardware 项目地址: https://gitcode.com/gh_mirrors/si/sistine Project Sistine是一个创新的开源项目,它能让普…...

F3D动画播放教程:如何轻松展示和播放3D模型动画

F3D动画播放教程:如何轻松展示和播放3D模型动画 【免费下载链接】f3d Fast and minimalist 3D viewer. 项目地址: https://gitcode.com/GitHub_Trending/f3/f3d 想要快速查看和播放3D模型动画吗?F3D(Fast and minimalist 3D viewer&am…...

EDK II代码质量门禁报告:全面解析门禁检查结果与最佳实践

EDK II代码质量门禁报告:全面解析门禁检查结果与最佳实践 【免费下载链接】edk2 EDK II 项目地址: https://gitcode.com/gh_mirrors/ed/edk2 EDK II作为现代、功能丰富的跨平台UEFI和PI规范固件开发环境,其代码质量门禁系统是确保固件可靠性和安全…...

brpc跨平台构建自动化:Jenkins与GitHub Actions终极指南

brpc跨平台构建自动化:Jenkins与GitHub Actions终极指南 【免费下载链接】brpc brpc is an Industrial-grade RPC framework using C Language, which is often used in high performance system such as Search, Storage, Machine learning, Advertisement, Recomm…...

MySQL局域网远程连接测试教程

MySQL局域网远程连接测试教程1本地服务器安装MySQL服务器,安装MySQL shell, Workbench(非必须)防火墙配置2远程访问用户电脑配置IP配置安装 Workbench客户端1本地服务器 安装MySQL服务器,安装MySQL shell, Workbench(非必须) 点击右下角的Advanced Opt…...

老旧设备的开源OCR解决方案:技术适配与性能优化指南

老旧设备的开源OCR解决方案:技术适配与性能优化指南 【免费下载链接】Umi-OCR Umi-OCR: 这是一个免费、开源、可批量处理的离线OCR软件,适用于Windows系统,支持截图OCR、批量OCR、二维码识别等功能。 项目地址: https://gitcode.com/GitHub…...

F3D开发环境搭建:从零开始编译和构建这个开源3D项目

F3D开发环境搭建:从零开始编译和构建这个开源3D项目 【免费下载链接】f3d Fast and minimalist 3D viewer. 项目地址: https://gitcode.com/GitHub_Trending/f3/f3d F3D是一款快速且极简的3D查看器,本指南将带你从零开始搭建其开发环境&#xff0…...

语音合成延迟优化:IndexTTS-2-LLM网络IO调优实战

语音合成延迟优化:IndexTTS-2-LLM网络IO调优实战 1. 为什么语音合成总在“等”?从用户卡顿说起 你有没有试过在语音合成页面点下“开始合成”,然后盯着进度条数秒——明明只是一句话,却要等3秒、5秒,甚至更久&#x…...

如何高效访问优质内容?bypass-paywalls-chrome-clean工具全方位使用指南

如何高效访问优质内容?bypass-paywalls-chrome-clean工具全方位使用指南 【免费下载链接】bypass-paywalls-chrome-clean 项目地址: https://gitcode.com/GitHub_Trending/by/bypass-paywalls-chrome-clean 在信息爆炸的数字时代,大量优质内容被…...

3步打造Windows字体终极体验:MacType高清渲染全攻略

3步打造Windows字体终极体验:MacType高清渲染全攻略 【免费下载链接】mactype Better font rendering for Windows. 项目地址: https://gitcode.com/gh_mirrors/ma/mactype 一、视觉痛点全解析:谁在忍受模糊字体的煎熬? 设计师的色彩…...

BootstrapBlazor通知组件:如何实现声音提示功能

BootstrapBlazor通知组件:如何实现声音提示功能 【免费下载链接】BootstrapBlazor 项目地址: https://gitcode.com/gh_mirrors/bo/BootstrapBlazor BootstrapBlazor是一个功能丰富的Blazor组件库,提供了各种UI组件来增强Web应用的用户体验。其中…...

Fish Speech 1.5入门指南:无需Python基础,5步完成高质量语音生成

Fish Speech 1.5入门指南:无需Python基础,5步完成高质量语音生成 你是不是也遇到过这些烦恼?想给视频配音,但自己的声音不好听,找配音员又太贵;想制作有声书,但录制过程繁琐,效果还…...

HP-Socket创新项目原型迭代记录:变更、原因与效果

HP-Socket创新项目原型迭代记录:变更、原因与效果 【免费下载链接】HP-Socket High Performance TCP/UDP/HTTP Communication Component 项目地址: https://gitcode.com/gh_mirrors/hp/HP-Socket HP-Socket作为一款高性能TCP/UDP/HTTP通信组件,其…...