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

news2026/3/27 5:55:00
前言在复杂的业务场景中我们经常需要使用多数据源来满足不同的数据访问需求。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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…