<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>MrRobot5</title>
    <description>MrRobot5 的个人主页</description>
    <link>https://mrrobot5.github.io/</link>
    <atom:link href="https://mrrobot5.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Sun, 30 Aug 2026 00:19:04 +0000</pubDate>
    <lastBuildDate>Sun, 30 Aug 2026 00:19:04 +0000</lastBuildDate>
    <generator>Jekyll v3.10.0</generator>
    
      <item>
        <title>JDBC setQueryTimeout 超时机制：H2 协作式取消与 MySQL KILL QUERY</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#业务背景&quot; id=&quot;markdown-toc-业务背景&quot;&gt;业务背景&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#h2-实现服务端协作式取消&quot; id=&quot;markdown-toc-h2-实现服务端协作式取消&quot;&gt;H2 实现：服务端协作式取消&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#超时设置链路&quot; id=&quot;markdown-toc-超时设置链路&quot;&gt;①超时设置链路&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#执行期取消cancelat--checkcanceled&quot; id=&quot;markdown-toc-执行期取消cancelat--checkcanceled&quot;&gt;②执行期取消：cancelAt + checkCanceled&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#mysql-驱动实现监控线程--kill-query&quot; id=&quot;markdown-toc-mysql-驱动实现监控线程--kill-query&quot;&gt;MySQL 驱动实现：监控线程 + KILL QUERY&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#启动监控任务&quot; id=&quot;markdown-toc-启动监控任务&quot;&gt;①启动监控任务&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#canceltaskkill-query&quot; id=&quot;markdown-toc-canceltaskkill-query&quot;&gt;②CancelTask：KILL QUERY&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#两种方案对比&quot; id=&quot;markdown-toc-两种方案对比&quot;&gt;两种方案对比&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#mybatis-应用defaultstatementtimeout&quot; id=&quot;markdown-toc-mybatis-应用defaultstatementtimeout&quot;&gt;MyBatis 应用：defaultStatementTimeout&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#总结&quot; id=&quot;markdown-toc-总结&quot;&gt;总结&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  交互式查询场景中，一条慢 SQL 可能长时间占用数据库连接，把整个系统拖垮。&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Statement.setQueryTimeout&lt;/code&gt; 可以作为保护手段：&lt;strong&gt;快速失败，而不是无限等待&lt;/strong&gt;。

  但”取消”到底由谁执行、如何执行，不同数据库差异很大。&lt;strong&gt;H2 是服务端协作式取消，MySQL 是客户端监控线程 + KILL QUERY&lt;/strong&gt;。

  最后结合 MyBatis 的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;defaultStatementTimeout&lt;/code&gt; 配置，看超时时间怎么发货作用。
&lt;/blockquote&gt;

&lt;h2 id=&quot;业务背景&quot;&gt;业务背景&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;交互式查询（如管理后台、报表）对响应时间敏感，超时设置让慢 SQL &lt;strong&gt;快速失败&lt;/strong&gt;，把错误及时暴露给用户。&lt;/li&gt;
  &lt;li&gt;若不加超时，慢 SQL 会长时间占用连接与锁，&lt;strong&gt;拖垮整个系统&lt;/strong&gt;，甚至引发雪崩。&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Statement.setQueryTimeout(int seconds)&lt;/code&gt; 是 JDBC 标准的超时入口，但落地方式因数据库而异。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;h2-实现服务端协作式取消&quot;&gt;H2 实现：服务端协作式取消&lt;/h2&gt;

&lt;blockquote&gt;
  H2 把超时实现为一条 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SET&lt;/code&gt; 命令，执行期间由算子循环周期性调用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;checkCanceled()&lt;/code&gt; 检查是否到期。

  🎈 &lt;strong&gt;协作式（cooperative）&lt;/strong&gt;的取消：依赖代码主动检查，一个长循环若没有检查点，可以”绕过”超时。
&lt;/blockquote&gt;

&lt;h3 id=&quot;超时设置链路&quot;&gt;①超时设置链路&lt;/h3&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;setQueryTimeout&lt;/code&gt; 并不是直接给 Statement 存个值，而是通过 JDBC 下发一条 SQL 命令 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SET QUERY_TIMEOUT ?&lt;/code&gt;：

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
    participant 应用 as 应用
    participant JDBC as JdbcStatement/Connection
    participant Set as Set 命令
    participant Session as Session

    应用-&amp;gt;&amp;gt;JDBC: 1. setQueryTimeout(1)
    JDBC-&amp;gt;&amp;gt;Set: prepareCommand(&quot;SET QUERY_TIMEOUT ?&quot;, 1000)
    Set-&amp;gt;&amp;gt;Session: session.setQueryTimeout()
    Note over Session: 限幅为 maxQueryTimeout，写 this.queryTimeout
    应用-&amp;gt;&amp;gt;JDBC: 2. executeQuery(...)
    JDBC-&amp;gt;&amp;gt;Session: Command.executeQuery → setCurrentCommand
    Note over Session: cancelAt = now + queryTimeout
    Session-&amp;gt;&amp;gt;Session: 3. 算子循环 checkCanceled()
    Note over Session: now &amp;gt;= cancelAt → 抛 STATEMENT_WAS_CANCELED
&lt;/code&gt;&lt;/pre&gt;

调用链上的关键类：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * JDBC 层入口：秒转毫秒，以 SET QUERY_TIMEOUT 命令下发
 * @see org.h2.jdbc.JdbcStatement#setQueryTimeout
 * @see org.h2.jdbc.JdbcConnection#setQueryTimeout
 */&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// JdbcStatement.setQueryTimeout(seconds) → JdbcConnection.setQueryTimeout(seconds * 1000)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// → prepareCommand(&quot;SET QUERY_TIMEOUT ?&quot;, ...) → Set.update() → session.setQueryTimeout&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 最终写入 session.queryTimeout（毫秒），并做全局限幅
 * @see org.h2.engine.Session#setQueryTimeout
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;setQueryTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;queryTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 取数据库全局配置，session 级不能超过它&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;database&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getSettings&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;maxQueryTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;queryTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;queryTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;queryTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;// 超限 → 按全局上限收口&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;queryTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;queryTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🎈 H2 的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;setQueryTimeout&lt;/code&gt; 作用于&lt;strong&gt;当前 Session&lt;/strong&gt;，且受全局配置 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;maxQueryTimeout&lt;/code&gt; 限幅。

&lt;h3 id=&quot;执行期取消cancelat--checkcanceled&quot;&gt;②执行期取消：cancelAt + checkCanceled&lt;/h3&gt;

执行查询时先记录”取消截止时间点”，供算子循环周期检查：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 执行前：session.setCurrentCommand 计算 cancelAt = now + queryTimeout
 * @see org.h2.command.Command#executeQuery
 * @see org.h2.engine.Session#setCurrentCommand
 */&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;session&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;setCurrentCommand&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 若 queryTimeout &amp;gt; 0 → cancelAt = 当前时间 + queryTimeout&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 周期性检查：now &amp;gt;= cancelAt 则中断查询
 * @see org.h2.engine.Session#checkCanceled
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;checkCanceled&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;now&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getCurrentTimeNanos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cancelAt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;now&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cancelAt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DbException&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ErrorCode&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;STATEMENT_WAS_CANCELED&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🙉 &lt;strong&gt;协作式取消的代价&lt;/strong&gt;：取消依赖算子代码主动调用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;checkCanceled()&lt;/code&gt;。若某段代码是一个不含检查点的长循环（如纯 CPU 计算、大结果集组装），超时期间不会被中断，只能等它自然结束。

&lt;h2 id=&quot;mysql-驱动实现监控线程--kill-query&quot;&gt;MySQL 驱动实现：监控线程 + KILL QUERY&lt;/h2&gt;

&lt;blockquote&gt;
  MySQL 与 H2 思路完全相反：&lt;strong&gt;客户端&lt;/strong&gt;驱动在发起查询前启动一个监控定时任务，超时后另开连接执行 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;KILL QUERY&lt;/code&gt; 中断服务端。
&lt;/blockquote&gt;

&lt;h3 id=&quot;启动监控任务&quot;&gt;①启动监控任务&lt;/h3&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 发起查询前，若启用且设置了超时，调度一个取消任务
 * @see com.mysql.jdbc.StatementImpl#executeQuery
 */&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;locallyScopedConn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getEnableQueryTimeouts&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;timeoutInMillis&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;locallyScopedConn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;versionMeetsMinimum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;timeoutTask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CancelTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;locallyScopedConn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getCancelTimer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;schedule&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;timeoutTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;timeoutInMillis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timeoutInMillis&lt;/code&gt; 由 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;setQueryTimeout(seconds)&lt;/code&gt; 提前换算好（&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seconds * 1000&lt;/code&gt;）。&lt;/li&gt;
  &lt;li&gt;定时器到点后触发 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CancelTask&lt;/code&gt;，其内部再&lt;strong&gt;另起线程&lt;/strong&gt;执行取消。&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;canceltaskkill-query&quot;&gt;②CancelTask：KILL QUERY&lt;/h3&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CancelTask&lt;/code&gt; 继承 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TimerTask&lt;/code&gt;，到点后 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;run()&lt;/code&gt; 内再启动一个取消线程，核心逻辑二选一：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 超时取消：要么直接杀连接，要么另开连接执行 KILL QUERY
 * @see com.mysql.jdbc.StatementImpl.CancelTask#run
 */&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;connection&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getQueryTimeoutKillsConnection&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// ① 配置 queryTimeoutKillsConnection=true → 直接关闭连接&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;toCancel&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;wasCancelled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;toCancel&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;wasCancelledByTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;connection&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;realClose&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MySQLStatementCancelledException&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(...));&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// ② 默认：复制连接属性，另开连接执行 KILL QUERY&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cancelConn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;connection&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;duplicate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;// URL 已变则回退 DriverManager.getConnection&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cancelStmt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cancelConn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;createStatement&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cancelStmt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;execute&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;KILL QUERY &quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;connectionId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;toCancel&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;wasCancelled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;toCancel&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;wasCancelledByTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

⭐ 关键点：

&lt;ul&gt;
  &lt;li&gt;取消用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;KILL QUERY &amp;lt;connectionId&amp;gt;&lt;/code&gt;（注意是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;QUERY&lt;/code&gt; 而非 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CONNECTION&lt;/code&gt;），只中断当前查询，&lt;strong&gt;不杀掉整个会话&lt;/strong&gt;。&lt;/li&gt;
  &lt;li&gt;取消发生在&lt;strong&gt;独立监控线程&lt;/strong&gt;上，主线程阻塞在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;execSQL&lt;/code&gt; 等服务端响应，收到中断后抛 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MySQLTimeoutException&lt;/code&gt;。&lt;/li&gt;
  &lt;li&gt;复制连接优先用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;connection.duplicate()&lt;/code&gt;；若原连接 URL 已变化，回退 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DriverManager.getConnection(origConnURL, origConnProps)&lt;/code&gt; 重建连接。&lt;/li&gt;
  &lt;li&gt;配置 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;queryTimeoutKillsConnection=true&lt;/code&gt; 时不再发 KILL QUERY，直接关闭连接，手段更激进。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;两种方案对比&quot;&gt;两种方案对比&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;维度&lt;/th&gt;
      &lt;th&gt;H2&lt;/th&gt;
      &lt;th&gt;MySQL 驱动&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;取消发起方&lt;/td&gt;
      &lt;td&gt;服务端（执行算子循环）&lt;/td&gt;
      &lt;td&gt;客户端（监控定时任务）&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;取消方式&lt;/td&gt;
      &lt;td&gt;协作式检查 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;checkCanceled()&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;新连接执行 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;KILL QUERY&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;取消粒度&lt;/td&gt;
      &lt;td&gt;查询内部检查点&lt;/td&gt;
      &lt;td&gt;服务端线程级中断&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;盲区&lt;/td&gt;
      &lt;td&gt;无检查点的长循环可”绕过”&lt;/td&gt;
      &lt;td&gt;服务端无响应时监控任务徒劳&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;额外开销&lt;/td&gt;
      &lt;td&gt;无&lt;/td&gt;
      &lt;td&gt;每次超时需新建连接执行 KILL&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;mybatis-应用defaultstatementtimeout&quot;&gt;MyBatis 应用：defaultStatementTimeout&lt;/h2&gt;

超时配置最常见的落点之一是 MyBatis，全局配置：

&lt;div class=&quot;language-xml highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nt&quot;&gt;&amp;lt;configuration&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;nt&quot;&gt;&amp;lt;settings&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;c&quot;&gt;&amp;lt;!-- 数据库查询/更新执行超过 5 秒仍未响应则超时 --&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;nt&quot;&gt;&amp;lt;setting&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;name=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;defaultStatementTimeout&quot;&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;value=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;5&quot;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;nt&quot;&gt;&amp;lt;/settings&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/configuration&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

创建 Statement 后，MyBatis 统一把超时值透传给 JDBC：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 设置 Statement 超时：优先 MappedStatement 级别，其次全局默认
 * @see org.apache.ibatis.executor.statement.BaseStatementHandler#setStatementTimeout
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;protected&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;setStatementTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Statement&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stmt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SQLException&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;timeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mappedStatement&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;timeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;stmt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;setQueryTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;timeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;// ① MappedStatement 级别&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;defaultTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;configuration&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getDefaultStatementTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;defaultTimeout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;stmt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;setQueryTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;defaultTimeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;// ② 全局默认&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🎈 优先级：&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MappedStatement.getTimeout()&lt;/code&gt; &amp;gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;configuration.getDefaultStatementTimeout()&lt;/code&gt; &amp;gt; 不设置。

&lt;h2 id=&quot;总结&quot;&gt;总结&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;落地方式差异巨大：&lt;strong&gt;H2 走服务端协作式取消&lt;/strong&gt;（&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SET QUERY_TIMEOUT&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;checkCanceled()&lt;/code&gt;），&lt;strong&gt;MySQL 走客户端监控线程 + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;KILL QUERY&lt;/code&gt;&lt;/strong&gt;。&lt;/li&gt;
  &lt;li&gt;H2 的协作式取消依赖算子主动检查，&lt;strong&gt;无检查点的长循环可以绕过超时&lt;/strong&gt;；MySQL 的取消独立于主线程，但依赖网络可达与连接复制。&lt;/li&gt;
  &lt;li&gt;MyBatis 通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;defaultStatementTimeout&lt;/code&gt; 将超时统一透传到 JDBC，实现”一处配置、全局生效”。&lt;/li&gt;
  &lt;li&gt;交互式查询场景务必配置合理超时，让慢 SQL &lt;strong&gt;快速失败&lt;/strong&gt;，避免连接与锁被长期占用。&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Sat, 29 Aug 2026 02:00:00 +0000</pubDate>
        <link>https://mrrobot5.github.io/2026/08/29/Insight-JDBC-queryTimeout-H2-and-Mysql/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2026/08/29/Insight-JDBC-queryTimeout-H2-and-Mysql/</guid>
        
        <category>JDBC</category>
        
        <category>h2数据库</category>
        
        <category>Mysql</category>
        
        <category>事务控制</category>
        
        
        <category>源码阅读</category>
        
      </item>
    
      <item>
        <title>H2 MVTable MVCC — UPDATE 拆解与 undoLog 回溯链</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#架构速览&quot; id=&quot;markdown-toc-架构速览&quot;&gt;架构速览&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#核心数据结构versionedvalue&quot; id=&quot;markdown-toc-核心数据结构versionedvalue&quot;&gt;核心数据结构：VersionedValue&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#更新机制先-undo再数据&quot; id=&quot;markdown-toc-更新机制先-undo再数据&quot;&gt;更新机制：先 undo、再数据&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#update-的本质&quot; id=&quot;markdown-toc-update-的本质&quot;&gt;UPDATE 的本质&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#undolog-回溯链&quot; id=&quot;markdown-toc-undolog-回溯链&quot;&gt;undoLog 回溯链&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#并发场景-debug-sql&quot; id=&quot;markdown-toc-并发场景-debug-sql&quot;&gt;并发场景 Debug SQL&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#update-数据变化演示&quot; id=&quot;markdown-toc-update-数据变化演示&quot;&gt;UPDATE 数据变化演示&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#提交与回滚机制&quot; id=&quot;markdown-toc-提交与回滚机制&quot;&gt;提交与回滚机制&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#commit&quot; id=&quot;markdown-toc-commit&quot;&gt;COMMIT&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#rollback&quot; id=&quot;markdown-toc-rollback&quot;&gt;ROLLBACK&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#总结&quot; id=&quot;markdown-toc-总结&quot;&gt;总结&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  上一篇《Insight h2database MVStore Table 新存储引擎 MVCC 实现原理》梳理了 MVTable 的整体架构与可见性机制。

  本文聚焦 &lt;strong&gt;UPDATE 操作在 MVTable 中的执行细节&lt;/strong&gt;。

  与直觉上的”原地修改某个字段”不同，MVTable 将 UPDATE &lt;strong&gt;拆解为 remove 旧行 + add 新行两步&lt;/strong&gt;，每一步都遵循 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt; 的”先写 undo、再写数据”。

  巧妙的是：&lt;strong&gt;undoLog 中每条 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;VersionedValue#value&lt;/code&gt; 是前一步 data 的值&lt;/strong&gt;，由此 undoLog 串成一条可从最新值回溯到最初已提交版本的单向链。
&lt;/blockquote&gt;

&lt;h2 id=&quot;架构速览&quot;&gt;架构速览&lt;/h2&gt;

先用一张表回顾 MVTable 与 RegularTable 的核心差异：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;维度&lt;/th&gt;
      &lt;th&gt;RegularTable（旧）&lt;/th&gt;
      &lt;th&gt;MVTable（新/默认）&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;多版本载体&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;row.sessionId&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;row.deleted&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;VersionedValue.operationId&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;未提交数据存放&lt;/td&gt;
      &lt;td&gt;内存 delta 集合&lt;/td&gt;
      &lt;td&gt;持久化 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undoLog&lt;/code&gt;（write-ahead）&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;冲突检测&lt;/td&gt;
      &lt;td&gt;行属性对比 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sessionId&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt; 比对 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operationId&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;可见性回溯&lt;/td&gt;
      &lt;td&gt;delta 过滤&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undoLog&lt;/code&gt; 单向链表回溯&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;blockquote&gt;
  👉 完整对比见《H2 数据库 MVStore 与 Regular 存储引擎对比》
&lt;/blockquote&gt;

&lt;h2 id=&quot;核心数据结构versionedvalue&quot;&gt;核心数据结构：VersionedValue&lt;/h2&gt;

MVTable 把版本信息编码进每个值自身，而非行对象上：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 数据 MVMap 中存储的值，不是裸值，而是带版本的包装
 * @see org.h2.mvstore.db.TransactionStore.VersionedValue
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;operationId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// transactionId(高位) + logId(低位)，0 表示已提交&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;// 真正的行数据，null 表示删除标记&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operationId == 0&lt;/code&gt; → 已提交，全体事务可见&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operationId != 0&lt;/code&gt; → 属于某个未提交事务，对其他事务隔离&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operationId&lt;/code&gt; 字段，同时承担了隔离（可见性判定）与锁（冲突检测）两个职责。&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;更新机制先-undo再数据&quot;&gt;更新机制：先 undo、再数据&lt;/h2&gt;

所有写入（Insert / Update / Delete）最终都汇聚到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt;，它是冲突检测的唯一入口：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 尝试写入/删除值。若该 key 被其他未提交事务占用，返回 false
 * @see org.h2.mvstore.db.TransactionStore.TransactionMap#trySet
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;boolean&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;trySet&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;K&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;boolean&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;onlyIfUnchanged&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;operationId&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getOperationId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;transactionId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;logId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;current&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// ① 全新 key：先写 undo → 再 putIfAbsent&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mapId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;// undo 存 null&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;putIfAbsent&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;logUndo&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getTransactionId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;current&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;operationId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// ② 已有已提交值：先写 undo（旧值） → 再 CAS 覆盖&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mapId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;// undo 存 旧值&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;logUndo&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;transactionId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// ③ 本事务自己改过：允许重入覆盖&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mapId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;logUndo&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// ★ 属于其他未提交事务 → 并发冲突&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

设计模式（write-ahead 原则）：

⭐ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transaction.log(mapId, key, current)&lt;/code&gt; &lt;strong&gt;总是在数据变更前执行&lt;/strong&gt; —— 先把”修改前的值”记入 undoLog，再修改 data MVMap。

&lt;h2 id=&quot;update-的本质&quot;&gt;UPDATE 的本质&lt;/h2&gt;

🎈 MVTable 处理 UPDATE 并不是”原地改一个值”，而是拆成 &lt;strong&gt;两次 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt; 调用&lt;/strong&gt;，每次对应一个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logId&lt;/code&gt;：

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
    participant 调用方 as MVTable.updateRow
    participant 主键索引 as MVPrimaryIndex
    participant txMap as TransactionMap

    调用方-&amp;gt;&amp;gt;主键索引: 1. 删除旧行 removeRow(row)
    主键索引-&amp;gt;&amp;gt;txMap: trySet(key, null) · logId=0
    Note over txMap: undo 记旧值 → data 写 null(删除标记)
    调用方-&amp;gt;&amp;gt;主键索引: 2. 插入新行 addRow(newRow)
    主键索引-&amp;gt;&amp;gt;txMap: trySet(key, newValue) · logId=1
    Note over txMap: undo 记 null(删除标记) → data 写新行
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;undolog-回溯链&quot;&gt;undoLog 回溯链&lt;/h2&gt;

🎈 此为全文最核心的设计：

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;undoLog 单向回溯链：
  bjz (op=operationId_1)
    → 查 undoLog[operationId_1] → oldValue = null (op=operationId_0)
    → 查 undoLog[operationId_0] → oldValue = bjn (op=0, 链尾，已提交)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

每条 undo 记录的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;VersionedValue#value&lt;/code&gt;（即 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;d[2]&lt;/code&gt;），&lt;strong&gt;恰好是上一步 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt; 写入 data 的值&lt;/strong&gt;。由此 undoLog 自然串成一条&lt;strong&gt;可回溯的单向链&lt;/strong&gt;。

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 可见性回溯：顺 operationId 在 undoLog 中查找&quot;被覆盖前的值&quot;
 * @see org.h2.mvstore.db.TransactionStore.TransactionMap#getValue
 */&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;getValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;K&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;maxLog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;id&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;operationId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;                        &lt;span class=&quot;c1&quot;&gt;// 已提交 → 可见&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getTransactionId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;transactionId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;getLogId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;maxLog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;// 本事务自己的修改 → 可见&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 其他未提交事务 → 从 undoLog 回溯到上一个版本&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;store&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;undoLog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;id&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// d[2] 即 oldValue&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 循环直到拿到一个可见版本&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🙉 注意：&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;getValue&lt;/code&gt; 不回走”原始 MVMap”（因 MVStore 是 Copy-on-Write），而是通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undoLog&lt;/code&gt; 中记录的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;oldValue(VersionedValue)&lt;/code&gt; 拿到历史版本。&lt;strong&gt;越靠近链尾的值越接近最初状态。&lt;/strong&gt;

&lt;h2 id=&quot;并发场景-debug-sql&quot;&gt;并发场景 Debug SQL&lt;/h2&gt;

以下用两个浏览器 Session 模拟并发 UPDATE，观察 MVCC 行为：

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;-- 建表并初始化数据&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;CREATE&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;TABLE&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;city&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;id&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;INT&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NOT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NULL&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AUTO_INCREMENT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;PRIMARY&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;KEY&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;code&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;VARCHAR&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NOT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NULL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;VARCHAR&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NOT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NULL&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;INSERT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;INTO&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;city&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;VALUES&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;bjx&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;北京西&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;INSERT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;INTO&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;city&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;VALUES&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;bjn&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;北京南&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;-- Session A：开启事务，更新 id=2&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;SET&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AUTOCOMMIT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;OFF&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;UPDATE&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;city&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;SET&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;code&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;bjz&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;WHERE&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;id&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;-- Session A 事务内查询 → 看到 bjz（自己的修改）&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;SELECT&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;FROM&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;city&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;WHERE&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;id&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;-- 结果: id=2, code=&apos;bjz&apos;, name=&apos;北京南&apos;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

此时 data MVMap 中 id=2 的值为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;VersionedValue{operationId=txA_log1, value=(2,&apos;bjz&apos;,&apos;北京南&apos;)}&lt;/code&gt;，undoLog 有 2 条记录。

&lt;div class=&quot;language-sql highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;-- Session B：查询同一条数据 → 通过 undoLog 回溯，仍看到 bjn&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;SELECT&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;FROM&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;city&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;WHERE&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;id&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;-- 结果: id=2, code=&apos;bjn&apos;, name=&apos;北京南&apos;  → 读到旧版本 ✔&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;-- Session B：尝试并发更新同一条数据&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;UPDATE&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;city&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;SET&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;code&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s1&quot;&gt;&apos;sjx&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;WHERE&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;id&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;-- ❌ 报错: CONCURRENT_UPDATE_1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

⭐ 并发流程解读：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Session B&lt;/th&gt;
      &lt;th&gt;底层机制&lt;/th&gt;
      &lt;th&gt;结果&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SELECT&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;getValue&lt;/code&gt; 检测到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operationId&lt;/code&gt; 属于 txA → 顺 undoLog 回溯 → 读到链尾 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bjn(op=0)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;读到旧值 ✔&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UPDATE&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt; 检测到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operationId&lt;/code&gt; 属于 txA ≠ txB → 返回 false → 上层抛 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CONCURRENT_UPDATE_1&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;并发冲突 ❌&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;update-数据变化演示&quot;&gt;UPDATE 数据变化演示&lt;/h2&gt;

demo 演示了同一事务内 UPDATE 的完整状态变化，可逐步查看 undoLog 与 data MVMap 的实时联动：

&lt;html lang=&quot;zh-CN&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot; /&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
&lt;title&gt;H2 MVTable UPDATE 数据变化全过程&lt;/title&gt;
&lt;style&gt;
  * { box-sizing: border-box; margin: 0; padding: 0; }
  .wrap { max-width: 1100px; margin: 0 auto; }
  .sub { color: #8b949e; font-size: 14px; margin-bottom: 20px; }
  .sql {
    background: #161b22; border: 1px solid #30363d; border-radius: 8px;
    padding: 12px 16px; font-family: &quot;SF Mono&quot;, Menlo, Consolas, monospace;
    font-size: 14px; color: #79c0ff; margin-bottom: 20px;
  }
  .controls { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 8px; }
  button {
    background: #21262d; color: #c9d1d9; border: 1px solid #30363d;
    border-radius: 6px; padding: 8px 16px; font-size: 14px; cursor: pointer;
    transition: .15s;
  }
  button:hover:not(:disabled) { background: #30363d; border-color: #58a6ff; }
  button:disabled { opacity: .4; cursor: not-allowed; }
  button.primary { background: #238636; border-color: #2ea043; }
  button.primary:hover:not(:disabled) { background: #2ea043; }
  button.danger { background: #6e2222; border-color: #8b3232; }
  button.danger:hover:not(:disabled) { background: #8b3232; }
  .stage-label {
    margin: 14px 0 18px; font-size: 15px; color: #d29922;
    background: #1c1a12; border-left: 3px solid #d29922; padding: 8px 14px;
    border-radius: 0 6px 6px 0;
  }
  .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
  @media (max-width: 800px) { .grid { grid-template-columns: 1fr; } }
  .panel {
    background: #161b22; border: 1px solid #30363d; border-radius: 10px;
    padding: 16px; min-height: 220px;
  }
  .panel h2 {
    font-size: 15px; color: #58a6ff; margin-bottom: 12px;
    display: flex; align-items: center; gap: 8px;
  }
  .panel h2 .tag {
    font-size: 11px; background: #30363d; color: #8b949e;
    padding: 2px 8px; border-radius: 10px; font-weight: normal;
  }
  .kv {
    font-family: &quot;SF Mono&quot;, Menlo, Consolas, monospace; font-size: 13px;
    border: 1px solid #30363d; border-radius: 8px; padding: 12px;
    margin-bottom: 10px; background: #0d1117; transition: .3s;
  }
  .kv.flash { border-color: #d29922; box-shadow: 0 0 0 2px rgba(210,153,34,.25); }
  .kv .row { display: flex; justify-content: space-between; padding: 2px 0; }
  .kv .k { color: #8b949e; }
  .committed { border-color: #2ea043 !important; }
  .committed .badge { color: #3fb950; }
  .uncommitted .badge { color: #d29922; }
  .deleted .badge { color: #f85149; }
  .badge { font-size: 11px; padding: 1px 8px; border-radius: 10px; border: 1px solid currentColor; }
  .value-bjn { color: #a5d6ff; }
  .value-bjz { color: #ffab70; }
  .value-null { color: #f85149; }
  .empty { color: #6e7681; font-style: italic; padding: 20px; text-align: center; }
  .chain {
    margin-top: 14px; font-family: monospace; font-size: 12px; color: #8b949e;
  }
  .chain .arrow { color: #d29922; margin: 0 6px; }
  .note {
    font-size: 12px; color: #6e7681; margin-top: 10px; line-height: 1.5;
  }
  .opid { color: #d2a8ff; }
  .steps { display: flex; gap: 4px; margin-bottom: 16px; flex-wrap: wrap; }
  .step-dot {
    flex: 1; min-width: 90px; text-align: center; font-size: 11px;
    padding: 6px 4px; border-radius: 6px; background: #161b22;
    border: 1px solid #30363d; color: #6e7681;
  }
  .step-dot.active { background: #1f6feb33; border-color: #58a6ff; color: #58a6ff; }
  .step-dot.done { color: #3fb950; border-color: #238636; }
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class=&quot;wrap&quot;&gt;
  &lt;h1&gt;H2 MVTable — UPDATE 数据变化全过程&lt;/h1&gt;
  &lt;div class=&quot;sub&quot;&gt;跟踪 &lt;code&gt;undoLog&lt;/code&gt; 与数据 MVMap 中 VersionedValue 的实时变化 · 事务 tx5&lt;/div&gt;
  &lt;div class=&quot;sql&quot;&gt;SET AUTOCOMMIT OFF;&lt;br /&gt;update city set code = &apos;bjz&apos; where id = 2;&amp;nbsp;&amp;nbsp;-- &apos;bjn&apos; → &apos;bjz&apos;&lt;/div&gt;

  &lt;div class=&quot;steps&quot; id=&quot;steps&quot;&gt;&lt;/div&gt;

  &lt;div class=&quot;controls&quot;&gt;
    &lt;button id=&quot;btnPrev&quot;&gt;‹ 上一步&lt;/button&gt;
    &lt;button id=&quot;btnNext&quot; class=&quot;primary&quot;&gt;下一步 ›&lt;/button&gt;
    &lt;button id=&quot;btnReset&quot;&gt;↺ 重置&lt;/button&gt;
    &lt;span style=&quot;flex:1&quot;&gt;&lt;/span&gt;
    &lt;button id=&quot;btnCommit&quot; class=&quot;primary&quot;&gt;模拟 COMMIT&lt;/button&gt;
    &lt;button id=&quot;btnRollback&quot; class=&quot;danger&quot;&gt;模拟 ROLLBACK&lt;/button&gt;
  &lt;/div&gt;

  &lt;div class=&quot;stage-label&quot; id=&quot;stageLabel&quot;&gt;&lt;/div&gt;

  &lt;div class=&quot;grid&quot;&gt;
    &lt;div class=&quot;panel&quot;&gt;
      &lt;h2&gt;data MVMap &lt;span class=&quot;tag&quot;&gt;key = 2 (主键 id)&lt;/span&gt;&lt;/h2&gt;
      &lt;div id=&quot;dataPanel&quot;&gt;&lt;/div&gt;
      &lt;div class=&quot;chain&quot; id=&quot;chainView&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;panel&quot;&gt;
      &lt;h2&gt;undoLog &lt;span class=&quot;tag&quot;&gt;[mapId, key, oldValue]&lt;/span&gt;&lt;/h2&gt;
      &lt;div id=&quot;undoPanel&quot;&gt;&lt;/div&gt;
      &lt;div class=&quot;note&quot; id=&quot;undoNote&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
const OP0 = &quot;5497558138880&quot;; // tx5, logId=0
const OP1 = &quot;5497558138881&quot;; // tx5, logId=1

// 每个阶段的完整状态快照
const stages = [
  {
    name: &quot;阶段 0 · 事务前&quot;,
    desc: &quot;数据 MVMap 中 key=2 是一行已提交数据,operationId=0 对所有事务可见;undoLog 为空。&quot;,
    data: { value: &quot;(2,&apos;bjn&apos;,北京市)&quot;, op: &quot;0&quot;, state: &quot;committed&quot; },
    undo: []
  },
  {
    name: &quot;阶段 1 · logId=0 · 删除旧行&quot;,
    desc: &quot;trySet 先把当前已提交值(bjn)写入 undoLog(write-ahead),再把 data 置为删除标记 value=null,operationId=&quot; + OP0 + &quot;。&quot;,
    data: { value: &quot;null (删除标记)&quot;, op: OP0, state: &quot;deleted&quot;, flash: true },
    undo: [
      { key: OP0, mapId: 8, k: 2, oldValue: &quot;(2,&apos;bjn&apos;,北京市)&quot;, oldOp: &quot;0&quot;, flash: true }
    ]
  },
  {
    name: &quot;阶段 2 · logId=1 · 插入新行(题图时刻)&quot;,
    desc: &quot;trySet 把阶段1的删除标记写入第2条 undo,再写入新行 bjz,operationId=&quot; + OP1 + &quot;。此时 undoLog.size=2,即调试器题图。&quot;,
    data: { value: &quot;(2,&apos;bjz&apos;,北京市)&quot;, op: OP1, state: &quot;uncommitted&quot;, flash: true },
    undo: [
      { key: OP0, mapId: 8, k: 2, oldValue: &quot;(2,&apos;bjn&apos;,北京市)&quot;, oldOp: &quot;0&quot; },
      { key: OP1, mapId: 8, k: 2, oldValue: &quot;null (删除标记)&quot;, oldOp: OP0, flash: true }
    ]
  }
];

const commitStage = {
  name: &quot;终态 · COMMIT&quot;,
  desc: &quot;遍历本事务 undo,把 data 里对应值的 operationId 清零(转为已提交),并清空 undoLog。bjz 成为新的已提交版本。&quot;,
  data: { value: &quot;(2,&apos;bjz&apos;,北京市)&quot;, op: &quot;0&quot;, state: &quot;committed&quot;, flash: true },
  undo: []
};
const rollbackStage = {
  name: &quot;终态 · ROLLBACK&quot;,
  desc: &quot;从大 logId 到小 logId 倒序遍历 undo,用 oldValue 逐级还原:先还原为删除标记,再还原为 bjn。最终如同 UPDATE 从未发生。&quot;,
  data: { value: &quot;(2,&apos;bjn&apos;,北京市)&quot;, op: &quot;0&quot;, state: &quot;committed&quot;, flash: true },
  undo: []
};

let idx = 0;
let terminal = null; // &apos;commit&apos; | &apos;rollback&apos; | null

function valClass(v) {
  if (v.indexOf(&apos;null&apos;) === 0) return &apos;value-null&apos;;
  if (v.indexOf(&apos;bjz&apos;) &gt;= 0) return &apos;value-bjz&apos;;
  return &apos;value-bjn&apos;;
}
function stateBadge(s) {
  if (s === &apos;committed&apos;) return &apos;已提交&apos;;
  if (s === &apos;deleted&apos;) return &apos;删除标记&apos;;
  return &apos;未提交 tx5&apos;;
}

function render() {
  const st = terminal === &apos;commit&apos; ? commitStage
           : terminal === &apos;rollback&apos; ? rollbackStage
           : stages[idx];

  // steps
  const stepEl = document.getElementById(&apos;steps&apos;);
  stepEl.innerHTML = stages.map((s, i) =&gt; {
    let cls = &apos;step-dot&apos;;
    if (!terminal) { if (i &lt; idx) cls += &apos; done&apos;; if (i === idx) cls += &apos; active&apos;; }
    else cls += &apos; done&apos;;
    return `&lt;div class=&quot;${cls}&quot;&gt;${s.name.split(&apos;·&apos;)[0].trim()}&lt;/div&gt;`;
  }).join(&apos;&apos;) + `&lt;div class=&quot;step-dot ${terminal?&apos;active&apos;:&apos;&apos;}&quot;&gt;终态&lt;/div&gt;`;

  document.getElementById(&apos;stageLabel&apos;).textContent = st.name + &apos; — &apos; + st.desc;

  // data panel
  const d = st.data;
  document.getElementById(&apos;dataPanel&apos;).innerHTML =
    `&lt;div class=&quot;kv ${d.state} ${d.flash?&apos;flash&apos;:&apos;&apos;}&quot;&gt;
      &lt;div class=&quot;row&quot;&gt;&lt;span class=&quot;k&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;${valClass(d.value)}&quot;&gt;${d.value}&lt;/span&gt;&lt;/div&gt;
      &lt;div class=&quot;row&quot;&gt;&lt;span class=&quot;k&quot;&gt;operationId&lt;/span&gt;&lt;span class=&quot;opid&quot;&gt;${d.op}&lt;/span&gt;&lt;/div&gt;
      &lt;div class=&quot;row&quot;&gt;&lt;span class=&quot;k&quot;&gt;状态&lt;/span&gt;&lt;span class=&quot;badge&quot;&gt;${stateBadge(d.state)}&lt;/span&gt;&lt;/div&gt;
    &lt;/div&gt;`;

  // chain view
  const chainEl = document.getElementById(&apos;chainView&apos;);
  if (st.undo.length === 2) {
    chainEl.innerHTML = &apos;回溯链:&lt;br&gt;bjz(op=…881)&lt;span class=&quot;arrow&quot;&gt;→&lt;/span&gt;null(op=…880)&lt;span class=&quot;arrow&quot;&gt;→&lt;/span&gt;bjn(op=0,链尾可见)&apos;;
  } else if (st.undo.length === 1) {
    chainEl.innerHTML = &apos;回溯链:&lt;br&gt;null(op=…880)&lt;span class=&quot;arrow&quot;&gt;→&lt;/span&gt;bjn(op=0,链尾可见)&apos;;
  } else {
    chainEl.innerHTML = &apos;&apos;;
  }

  // undo panel
  const up = document.getElementById(&apos;undoPanel&apos;);
  if (st.undo.length === 0) {
    up.innerHTML = &apos;&lt;div class=&quot;empty&quot;&gt;undoLog 为空 (size = 0)&lt;/div&gt;&apos;;
  } else {
    up.innerHTML = st.undo.map(u =&gt;
      `&lt;div class=&quot;kv ${u.flash?&apos;flash&apos;:&apos;&apos;}&quot;&gt;
        &lt;div class=&quot;row&quot;&gt;&lt;span class=&quot;k&quot;&gt;key (opId)&lt;/span&gt;&lt;span class=&quot;opid&quot;&gt;${u.key}&lt;/span&gt;&lt;/div&gt;
        &lt;div class=&quot;row&quot;&gt;&lt;span class=&quot;k&quot;&gt;[0] mapId&lt;/span&gt;&lt;span&gt;${u.mapId}&lt;/span&gt;&lt;/div&gt;
        &lt;div class=&quot;row&quot;&gt;&lt;span class=&quot;k&quot;&gt;[1] key&lt;/span&gt;&lt;span&gt;${u.k}&lt;/span&gt;&lt;/div&gt;
        &lt;div class=&quot;row&quot;&gt;&lt;span class=&quot;k&quot;&gt;[2] oldValue&lt;/span&gt;&lt;span class=&quot;${valClass(u.oldValue)}&quot;&gt;${u.oldValue}&lt;/span&gt;&lt;/div&gt;
        &lt;div class=&quot;row&quot;&gt;&lt;span class=&quot;k&quot;&gt;oldValue.op&lt;/span&gt;&lt;span class=&quot;opid&quot;&gt;${u.oldOp}&lt;/span&gt;&lt;/div&gt;
      &lt;/div&gt;`).join(&apos;&apos;);
  }
  document.getElementById(&apos;undoNote&apos;).textContent =
    st.undo.length ? &apos;size = &apos; + st.undo.length + &apos; · 每条 oldValue 恰好是前一步 data 的值,串成回溯链&apos; : &apos;&apos;;

  // buttons
  document.getElementById(&apos;btnPrev&apos;).disabled = terminal || idx === 0;
  document.getElementById(&apos;btnNext&apos;).disabled = terminal || idx === stages.length - 1;
  document.getElementById(&apos;btnCommit&apos;).disabled = terminal === &apos;commit&apos;;
  document.getElementById(&apos;btnRollback&apos;).disabled = terminal === &apos;rollback&apos;;
}

document.getElementById(&apos;btnNext&apos;).onclick = () =&gt; { if (idx &lt; stages.length-1) idx++; render(); };
document.getElementById(&apos;btnPrev&apos;).onclick = () =&gt; { if (idx &gt; 0) idx--; render(); };
document.getElementById(&apos;btnReset&apos;).onclick = () =&gt; { idx = 0; terminal = null; render(); };
document.getElementById(&apos;btnCommit&apos;).onclick = () =&gt; { idx = stages.length-1; terminal = &apos;commit&apos;; render(); };
document.getElementById(&apos;btnRollback&apos;).onclick = () =&gt; { idx = stages.length-1; terminal = &apos;rollback&apos;; render(); };

render();
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

&lt;blockquote&gt;
  👉 点击”下一步”观察 logId=0（删除旧行）→ logId=1（插入新行）两个阶段中 undoLog 如何逐步增长，以及回溯链 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bjz → null → bjn&lt;/code&gt; 如何形成。

  👉 点击”模拟 COMMIT”观察：operationId 全部置零，undoLog 清空，新值成为已提交版本。
&lt;/blockquote&gt;

&lt;h2 id=&quot;提交与回滚机制&quot;&gt;提交与回滚机制&lt;/h2&gt;

&lt;h3 id=&quot;commit&quot;&gt;COMMIT&lt;/h3&gt;

提交的本质：把本事务所有改动值的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operationId&lt;/code&gt; 清零，并清空 undoLog：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * @see org.h2.mvstore.db.TransactionStore#commit
 */&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;commit&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Transaction&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;maxLogId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logId&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logId&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;maxLogId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;Long&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;undoKey&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getOperationId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;op&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;undoLog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;undoKey&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;MVMap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;map&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;openMap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;op&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]);&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;op&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;remove&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;              &lt;span class=&quot;c1&quot;&gt;// 删除标记 → 物理删除&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VersionedValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;v2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;// operationId 归零 → 全局可见&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;map&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;put&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;undoLog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;remove&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;undoKey&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;// 清理 undo&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;endTransaction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;rollback&quot;&gt;ROLLBACK&lt;/h3&gt;

回滚从大 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logId&lt;/code&gt; 向小 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logId&lt;/code&gt; 倒序遍历 undoLog，用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;oldValue&lt;/code&gt; 逐级还原：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * @see org.h2.mvstore.db.TransactionStore#rollbackTo
 */&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 遍历本事务的 undoLog，把每个 key 恢复成 oldValue&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 新增的删掉，修改/删除的还原&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

对于上例的 UPDATE（bjn → bjz）：
&lt;ol&gt;
  &lt;li&gt;取 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undoLog[operationId_1]&lt;/code&gt; → 还原为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null(op=operationId_0)&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;取 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undoLog[operationId_0]&lt;/code&gt; → 还原为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bjn(op=0)&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

逐级逆向走完这条链，data 回到最初状态，如同 UPDATE 从未发生。

&lt;h2 id=&quot;总结&quot;&gt;总结&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;MVTable 的 UPDATE &lt;strong&gt;不是原地修改&lt;/strong&gt;，而是拆成 &lt;strong&gt;remove 旧行 + add 新行&lt;/strong&gt; 两次 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt;，每次对应一个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logId&lt;/code&gt;。&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt; 遵循 &lt;strong&gt;write-ahead 原则&lt;/strong&gt;：每条数据写入前，先 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transaction.log()&lt;/code&gt; 把旧值记入 undoLog，保证崩溃后可恢复。&lt;/li&gt;
  &lt;li&gt;undoLog 中每条 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;VersionedValue#value&lt;/code&gt; 恰好是&lt;strong&gt;前一步 data 的值&lt;/strong&gt;，自然形成 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bjz → null → bjn&lt;/code&gt; 的单向回溯链，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;getValue&lt;/code&gt; 通过遍历此链实现多版本读。&lt;/li&gt;
  &lt;li&gt;并发冲突检测在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trySet&lt;/code&gt; 中通过比对 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operationId&lt;/code&gt; 实现：若目标值属于其他未提交事务即返回 false，上层转为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CONCURRENT_UPDATE_1&lt;/code&gt;。&lt;/li&gt;
  &lt;li&gt;undoLog 作为持久化的 MVMap，兼顾了回滚、快照回溯和崩溃恢复，与 MVStore 的 Copy-on-Write 特性天然契合。&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Tue, 11 Aug 2026 02:00:00 +0000</pubDate>
        <link>https://mrrobot5.github.io/2026/08/11/h2-mvtable-update-undo/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2026/08/11/h2-mvtable-update-undo/</guid>
        
        <category>h2数据库</category>
        
        <category>MVStore</category>
        
        <category>并发控制</category>
        
        <category>MVCC</category>
        
        
        <category>源码阅读</category>
        
      </item>
    
      <item>
        <title>事务提交与消息发送同步方案 — TransactionSynchronizationAdapter 实践</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#问题场景&quot; id=&quot;markdown-toc-问题场景&quot;&gt;问题场景&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#异常表现&quot; id=&quot;markdown-toc-异常表现&quot;&gt;异常表现&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#问题本质&quot; id=&quot;markdown-toc-问题本质&quot;&gt;问题本质&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#核心方案transactionsynchronizationadapter&quot; id=&quot;markdown-toc-核心方案transactionsynchronizationadapter&quot;&gt;核心方案：TransactionSynchronizationAdapter&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#-实现原理&quot; id=&quot;markdown-toc--实现原理&quot;&gt;① 实现原理&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-代码实现&quot; id=&quot;markdown-toc--代码实现&quot;&gt;② 代码实现&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-优点与不足&quot; id=&quot;markdown-toc--优点与不足&quot;&gt;③ 优点与不足&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#扩展应用transactionawarecachemanagerproxy&quot; id=&quot;markdown-toc-扩展应用transactionawarecachemanagerproxy&quot;&gt;扩展应用：TransactionAwareCacheManagerProxy&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#-问题背景&quot; id=&quot;markdown-toc--问题背景&quot;&gt;① 问题背景&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-实现原理-1&quot; id=&quot;markdown-toc--实现原理-1&quot;&gt;② 实现原理&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-使用方式&quot; id=&quot;markdown-toc--使用方式&quot;&gt;③ 使用方式&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#其他同步方案&quot; id=&quot;markdown-toc-其他同步方案&quot;&gt;其他同步方案&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#总结&quot; id=&quot;markdown-toc-总结&quot;&gt;总结&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  在日常业务开发中，经常需要在事务中完成数据库操作后，对外发送 MQ 消息通知下游消费。但在事务提交前就发送消息，消费者可能立即处理并查询数据库，此时事务还未提交，导致数据不一致。

  Spring 框架提供了 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationAdapter&lt;/code&gt; 作为最小代价的同步方案，在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 回调中执行外部交互，确保消息只在事务成功提交后才发送。

  本文将围绕该机制展开，同时扩展到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheManagerProxy&lt;/code&gt; 的应用场景，并简要介绍其他同步方案。
&lt;/blockquote&gt;

&lt;h2 id=&quot;问题场景&quot;&gt;问题场景&lt;/h2&gt;

&lt;h3 id=&quot;异常表现&quot;&gt;异常表现&lt;/h3&gt;

假设一个典型的业务场景：创建异常单并通知下游系统。

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
    participant 业务服务
    participant 数据库
    participant MQ消息队列
    participant 消费者

    业务服务-&amp;gt;&amp;gt;数据库: 1. 开启事务
    业务服务-&amp;gt;&amp;gt;数据库: 2. 插入业务记录
    业务服务-&amp;gt;&amp;gt;MQ消息队列: 3. 发送 MQ 消息
    业务服务-&amp;gt;&amp;gt;数据库: 4. 提交事务
    MQ消息队列-&amp;gt;&amp;gt;消费者: 5. 消息被立即消费
    消费者-&amp;gt;&amp;gt;数据库: 6. 查询数据
&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;❌&lt;/code&gt; 消息在事务提交前发出，消费者查不到刚写入的数据，导致处理异常&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;❌&lt;/code&gt; 如果事务最终回滚，消息已经发出且无法撤回，造成数据不一致&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;问题本质&quot;&gt;问题本质&lt;/h3&gt;

这是分布式系统中的&lt;strong&gt;事务与外部交互一致性&lt;/strong&gt;问题，核心矛盾在于：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;时序&lt;/th&gt;
      &lt;th&gt;消息发送时机&lt;/th&gt;
      &lt;th&gt;结果&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;事务提交前发消息&lt;/td&gt;
      &lt;td&gt;消息已送达，数据未落库&lt;/td&gt;
      &lt;td&gt;❌ 消费者查不到数据&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;事务提交后发消息&lt;/td&gt;
      &lt;td&gt;数据已落库，消息后发送&lt;/td&gt;
      &lt;td&gt;✅ 消费者可正常处理&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;🎈&lt;/code&gt; 不只 MQ 消息，任何在事务中需要与外部系统交互的场景（缓存更新、文件写入、RPC 调用等）都会面临同样的问题。

&lt;h2 id=&quot;核心方案transactionsynchronizationadapter&quot;&gt;核心方案：TransactionSynchronizationAdapter&lt;/h2&gt;

&lt;h3 id=&quot;-实现原理&quot;&gt;① 实现原理&lt;/h3&gt;

Spring 通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationManager&lt;/code&gt; 在事务生命周期中提供多个扩展点，允许注册自定义的同步回调：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;回调方法&lt;/th&gt;
      &lt;th&gt;触发时机&lt;/th&gt;
      &lt;th&gt;适用场景&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;事务已提交&lt;/td&gt;
      &lt;td&gt;✅ 发送 MQ、清除缓存&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCompletion(int status)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;事务结束&lt;/td&gt;
      &lt;td&gt;资源清理（区分提交/回滚）&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beforeCommit(boolean readOnly)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;事务提交前&lt;/td&gt;
      &lt;td&gt;最终校验&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beforeCompletion()&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;事务结束前&lt;/td&gt;
      &lt;td&gt;连接释放前的收尾工作&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;⭐&lt;/code&gt; 核心思路：在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 中执行消息发送，利用事务提交后再执行的特性，天然解决消息与数据的时序问题。

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
    participant 业务服务
    participant TransactionSynchronizationManager
    participant 数据库
    participant MQ消息队列

    业务服务-&amp;gt;&amp;gt;数据库: 1. 开启事务
    业务服务-&amp;gt;&amp;gt;数据库: 2. 执行业务操作
    业务服务-&amp;gt;&amp;gt;TransactionSynchronizationManager: 3. registerSynchronization&amp;lt;br/&amp;gt;(注册 afterCommit)
    业务服务-&amp;gt;&amp;gt;数据库: 4. 提交事务
    数据库--&amp;gt;&amp;gt;TransactionSynchronizationManager: 5. 事务提交成功
    TransactionSynchronizationManager-&amp;gt;&amp;gt;MQ消息队列: 6. 触发 afterCommit()&amp;lt;br/&amp;gt;发送 MQ 消息
&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;✔&lt;/code&gt; 消息发送时数据库操作已全部提交&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;✔&lt;/code&gt; 事务回滚时 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 不会被调用，消息不会错误发送&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-代码实现&quot;&gt;② 代码实现&lt;/h3&gt;

核心代码如下，通过在方法中判断当前是否存在活动事务，将消息发送注册到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 回调：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 发送 MQ 任务消息，确保在事务提交后执行
 *
 * @see org.springframework.transaction.support.TransactionSynchronizationAdapter#afterCommit
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MQTaskMessageBaseDto&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sendMQTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;TransactionSynchronizationManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;isSynchronizationActive&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 存在活动事务 → 注册 afterCommit 回调，延迟到事务提交后发送&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;TransactionSynchronizationManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;registerSynchronization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;TransactionSynchronizationAdapter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;nd&quot;&gt;@Override&lt;/span&gt;
                    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;afterCommit&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                        &lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;info&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;事务已提交，发送MQ消息:{}&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
                        &lt;span class=&quot;n&quot;&gt;doSendMQTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;});&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 不存在事务 → 直接发送&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;info&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;无事务上下文，直接发送MQ消息:{}&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;doSendMQTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;cm&quot;&gt;/**
 * 实际执行消息发送
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;doSendMQTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MQTaskMessageBaseDto&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 具体的 MQ 发送逻辑&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;🎈&lt;/code&gt; 注意：当 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationManager.isSynchronizationActive()&lt;/code&gt; 为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; 时（非事务场景），需要直接发送消息，避免回调永远不被触发。

&lt;h3 id=&quot;-优点与不足&quot;&gt;③ 优点与不足&lt;/h3&gt;

&lt;strong&gt;优点&lt;/strong&gt;：

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;✔&lt;/code&gt; Spring 原生支持，无需引入额外依赖&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;✔&lt;/code&gt; 实现简单，代码侵入性低&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;✔&lt;/code&gt; 无额外延迟，消息在事务提交后立即发送&lt;/li&gt;
&lt;/ul&gt;

&lt;strong&gt;不足&lt;/strong&gt;：

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;❌&lt;/code&gt; 消息发送失败不会影响已提交的事务，需要配合重试或补偿机制&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;❌&lt;/code&gt; 仅适用于单库事务，对分布式事务场景无能为力&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;❌&lt;/code&gt; 如果存在&lt;strong&gt;主从延迟&lt;/strong&gt;，消费者可能从从库读取到旧数据，仍会出现短暂不一致&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;❌&lt;/code&gt; 如果存在&lt;strong&gt;网络延迟&lt;/strong&gt;（消息到达延迟），需要额外的最终一致性保障&lt;/li&gt;
&lt;/ul&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;🙉&lt;/code&gt; 对于主从延迟和网络延迟问题，这不是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationAdapter&lt;/code&gt; 本身的缺陷，而是分布式系统固有的挑战。简单的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 无法感知这些延迟，需要引入更复杂的方案（如本地消息表 + 定时补偿）。

&lt;h2 id=&quot;扩展应用transactionawarecachemanagerproxy&quot;&gt;扩展应用：TransactionAwareCacheManagerProxy&lt;/h2&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheManagerProxy&lt;/code&gt; 是 Spring 基于同样的同步机制，解决&lt;strong&gt;缓存与事务不一致&lt;/strong&gt;问题的典型案例。

&lt;h3 id=&quot;-问题背景&quot;&gt;① 问题背景&lt;/h3&gt;

当使用非事务感知的缓存管理器（如 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SimpleCacheManager&lt;/code&gt;）时，如果先更新缓存再回滚事务：

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
    participant 业务服务
    participant 数据库
    participant 缓存

    业务服务-&amp;gt;&amp;gt;数据库: 1. 开启事务
    业务服务-&amp;gt;&amp;gt;缓存: 2. put(key, value)
    业务服务-&amp;gt;&amp;gt;数据库: 3. 事务回滚!
    Note over 缓存: ❌ 缓存中残留脏数据!&amp;lt;br/&amp;gt;数据库已是旧值
&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;❌&lt;/code&gt; 数据库回滚后数据恢复原值，但缓存中已写入新值，造成脏数据&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-实现原理-1&quot;&gt;② 实现原理&lt;/h3&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheManagerProxy&lt;/code&gt; 基于&lt;strong&gt;组合模式&lt;/strong&gt;，通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheDecorator&lt;/code&gt; 装饰目标 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cache&lt;/code&gt; 实例，将缓存写操作与 Spring 事务绑定：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * TransactionAwareCacheDecorator 核心逻辑（伪代码示意）
 *
 * @see org.springframework.cache.transaction.TransactionAwareCacheDecorator
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransactionAwareCacheDecorator&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;implements&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Cache&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targetCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 被装饰的真实 Cache&lt;/span&gt;

    &lt;span class=&quot;nd&quot;&gt;@Override&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;put&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;TransactionSynchronizationManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;isSynchronizationActive&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// 存在活动事务 → 注册 afterCommit 回调&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;TransactionSynchronizationManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;registerSynchronization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;TransactionSynchronizationAdapter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;nd&quot;&gt;@Override&lt;/span&gt;
                    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;afterCommit&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                        &lt;span class=&quot;n&quot;&gt;targetCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;put&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 事务提交后真正写入缓存&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;});&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;targetCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;put&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 非事务场景直接写入&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// ❌ evict、clear 等写操作同样延迟到 afterCommit&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;strong&gt;核心行为&lt;/strong&gt;：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;操作&lt;/th&gt;
      &lt;th&gt;存在活动事务时&lt;/th&gt;
      &lt;th&gt;无事务时&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;put(key, value)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;注册到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit&lt;/code&gt;，事务提交后才写入&lt;/td&gt;
      &lt;td&gt;立即写入&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;evict(key)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;注册到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit&lt;/code&gt;，事务提交后才清除&lt;/td&gt;
      &lt;td&gt;立即清除&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clear()&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;注册到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit&lt;/code&gt;，事务提交后才清空&lt;/td&gt;
      &lt;td&gt;立即清空&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get(key)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;直接读取（读操作不受事务影响）&lt;/td&gt;
      &lt;td&gt;直接读取&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;✔&lt;/code&gt; 事务回滚 → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 不会被调用 → 缓存保持旧值，与数据库一致&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;✔&lt;/code&gt; 事务提交 → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 被调用 → 缓存写入新值，与数据库一致&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-使用方式&quot;&gt;③ 使用方式&lt;/h3&gt;

通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheManagerProxy&lt;/code&gt; 包装已有的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CacheManager&lt;/code&gt;：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@Bean&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CacheManager&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;cacheManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CacheManager&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targetCacheManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 包装目标 CacheManager，使其具备事务感知能力&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;TransactionAwareCacheManagerProxy&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;targetCacheManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;🎈&lt;/code&gt; 如果使用了 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@EnableCaching&lt;/code&gt; 且配置了 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;JCacheCacheManager&lt;/code&gt;、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ConcurrentMapCacheManager&lt;/code&gt; 等非事务感知的实现，建议通过这种方式增强事务一致性。

&lt;h2 id=&quot;其他同步方案&quot;&gt;其他同步方案&lt;/h2&gt;

除了 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationAdapter&lt;/code&gt; 之外，针对事务与外部交互的同步问题，还有以下可选方案：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;方案&lt;/th&gt;
      &lt;th&gt;核心思路&lt;/th&gt;
      &lt;th&gt;适用场景&lt;/th&gt;
      &lt;th&gt;复杂度&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;本地消息表&lt;/td&gt;
      &lt;td&gt;将消息写入本地数据库表，定时扫描发送 + 确认消费&lt;/td&gt;
      &lt;td&gt;跨服务、需要最终一致性&lt;/td&gt;
      &lt;td&gt;⭐⭐⭐&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;RocketMQ 事务消息&lt;/td&gt;
      &lt;td&gt;利用 RocketMQ 事务消息机制，回查本地事务状态&lt;/td&gt;
      &lt;td&gt;已使用 RocketMQ 的场景&lt;/td&gt;
      &lt;td&gt;⭐⭐⭐&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;定时扫描补偿&lt;/td&gt;
      &lt;td&gt;定时扫描待发送/失败记录，进行补发&lt;/td&gt;
      &lt;td&gt;简单场景、对时效性要求不高&lt;/td&gt;
      &lt;td&gt;⭐⭐&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;事件溯源 (Event Sourcing)&lt;/td&gt;
      &lt;td&gt;以事件为事实源，状态从事件派生&lt;/td&gt;
      &lt;td&gt;复杂的领域模型&lt;/td&gt;
      &lt;td&gt;⭐⭐⭐⭐&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;TCC 分布式事务&lt;/td&gt;
      &lt;td&gt;Try-Confirm-Cancel 三阶段协议&lt;/td&gt;
      &lt;td&gt;严格的跨服务数据一致性&lt;/td&gt;
      &lt;td&gt;⭐⭐⭐⭐⭐&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;👉&lt;/code&gt; 方案选型建议：优先从最简单的方式开始。如果只是单库事务中的消息发送或缓存更新，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationAdapter&lt;/code&gt; 是最低成本的选择；当面临跨数据库、跨服务场景时，再考虑本地消息表或 RocketMQ 事务消息等方案。

&lt;h2 id=&quot;总结&quot;&gt;总结&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationAdapter&lt;/code&gt; 是 Spring 提供的最小代价方案，通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 将外部交互延迟到事务成功提交后，解决消息发送与数据不一致问题&lt;/li&gt;
  &lt;li&gt;除了 MQ 消息发送，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheManagerProxy&lt;/code&gt; 也是基于同样的同步机制，通过装饰模式将缓存写操作绑定到事务生命周期，避免事务回滚后的脏数据&lt;/li&gt;
  &lt;li&gt;任何在事务中的外部交互（MQ、缓存、RPC、文件写入）都应考虑使用事务同步回调来保障一致性&lt;/li&gt;
  &lt;li&gt;该方案无法解决主从延迟、网络延迟等分布式问题，这些场景需要通过本地消息表、定时补偿等更复杂的方案来保障最终一致性&lt;/li&gt;
  &lt;li&gt;方案选型应遵循”最小代价优先”原则，从简单开始逐步升级&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Tue, 04 Aug 2026 02:00:00 +0000</pubDate>
        <link>https://mrrobot5.github.io/2026/08/04/transaction-synchronization-message-sync/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2026/08/04/transaction-synchronization-message-sync/</guid>
        
        <category>Spring</category>
        
        <category>事务控制</category>
        
        <category>消息队列</category>
        
        
        <category>实战问题</category>
        
      </item>
    
      <item>
        <title>H2 数据库 MVStore 与 Regular 存储引擎对比</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#背景&quot; id=&quot;markdown-toc-背景&quot;&gt;背景&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#两条并行的存储栈&quot; id=&quot;markdown-toc-两条并行的存储栈&quot;&gt;两条并行的存储栈&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#存储实现&quot; id=&quot;markdown-toc-存储实现&quot;&gt;存储实现&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#-mvstore-栈&quot; id=&quot;markdown-toc--mvstore-栈&quot;&gt;① MVStore 栈&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-pagestore-栈&quot; id=&quot;markdown-toc--pagestore-栈&quot;&gt;② PageStore 栈&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#平行对应关系&quot; id=&quot;markdown-toc-平行对应关系&quot;&gt;平行对应关系&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#-表层&quot; id=&quot;markdown-toc--表层&quot;&gt;① 表层&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-事务层&quot; id=&quot;markdown-toc--事务层&quot;&gt;② 事务层&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-存储引擎层&quot; id=&quot;markdown-toc--存储引擎层&quot;&gt;③ 存储引擎层&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-逻辑数据结构层&quot; id=&quot;markdown-toc--逻辑数据结构层&quot;&gt;④ 逻辑数据结构层&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-文件-io-层&quot; id=&quot;markdown-toc--文件-io-层&quot;&gt;⑤ 文件 I/O 层&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#核心差异总结&quot; id=&quot;markdown-toc-核心差异总结&quot;&gt;核心差异总结&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#总结&quot; id=&quot;markdown-toc-总结&quot;&gt;总结&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  在深入阅读 H2 数据库源码时，会发现内部存在&lt;strong&gt;两套完全独立的存储实现&lt;/strong&gt;——&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt;。

  初次接触时容易混淆：同名类 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FileStore&lt;/code&gt; 为何分布在不同包下？&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Page&lt;/code&gt; 又是什么关系？

  本文通过&lt;strong&gt;层级对照&lt;/strong&gt;的方式，将两条并行的存储栈拉平对比，帮助建立起清晰的结构认知。&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; 为默认引擎，采用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVCC&lt;/code&gt; 机制；&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Regular&lt;/code&gt; 对应传统的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt; 栈。
&lt;/blockquote&gt;

&lt;h2 id=&quot;背景&quot;&gt;背景&lt;/h2&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Database&lt;/code&gt; 在启动时根据配置决定走哪条存储栈，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; 为当前默认选项：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// @see org.h2.engine.Database#open&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 依据配置 MV_STORE 决定使用哪套引擎&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dbSettings&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;mvStore&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 走 MVStore 栈（新）&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 走 PageStore 栈（旧）&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🎈 两套栈&lt;strong&gt;互不混用&lt;/strong&gt;，表引擎、存储层、文件 I/O 全是独立实现。理解这一点，就不会再把 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;org.h2.mvstore.FileStore&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;org.h2.store.FileStore&lt;/code&gt; 搞混了。

&lt;h2 id=&quot;两条并行的存储栈&quot;&gt;两条并行的存储栈&lt;/h2&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;graph TB
    DB[&quot;Database 数据库引擎&quot;]
    DB --&amp;gt;|MVCC/默认| MVStack[&quot;MVStore 栈&quot;]
    DB --&amp;gt;|传统| PSStack[&quot;PageStore 栈&quot;]

    subgraph MVStack[&quot;MVStore 存储栈 (新)&quot;]
        MVTable[&quot;MVTable extends TableBase&quot;]
        MVTable --&amp;gt; MVStore[&quot;MVStore 存储引擎&quot;]
        MVTable --&amp;gt; TxStore[&quot;TransactionStore 事务层&quot;]
        MVStore --&amp;gt; MVMap[&quot;MVMap 有序 K-V 树&quot;]
        MVStore --&amp;gt; MVFileStore[&quot;mvstore.FileStore&quot;]
        MVMap --&amp;gt; MVPage[&quot;mvstore.Page&quot;]
    end

    subgraph PSStack[&quot;PageStore 存储栈 (旧)&quot;]
        RegularTable[&quot;RegularTable extends TableBase&quot;]
        RegularTable --&amp;gt; PageStore[&quot;PageStore 存储引擎&quot;]
        PageStore --&amp;gt; PSFileStore[&quot;store.FileStore&quot;]
        PageStore --&amp;gt; PSPage[&quot;store.Page 固定页&quot;]
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  ⚠️ &lt;strong&gt;关键点&lt;/strong&gt;：&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;org.h2.mvstore.FileStore&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;org.h2.store.FileStore&lt;/code&gt; 是&lt;strong&gt;两个不同的类&lt;/strong&gt;，分属两套栈，互不相关。
&lt;/blockquote&gt;

&lt;h2 id=&quot;存储实现&quot;&gt;存储实现&lt;/h2&gt;

&lt;h3 id=&quot;-mvstore-栈&quot;&gt;① MVStore 栈&lt;/h3&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// MVMap 属于 MVStore&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MVMap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;MVStore&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;store&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// MVStore 管理多个 MVMap&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MVStore&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;ConcurrentHashMap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MVMap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;?,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;?&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;maps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;FileStore&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fileStore&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;// 底层 I/O&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;MVMap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;meta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 元信息 map&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// MVTable 持有 TransactionStore&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MVTable&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TableBase&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;TransactionStore&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;store&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 主键/索引数据落在若干 MVMap 上&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

核心关系：

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap.store&lt;/code&gt; → 每个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt; &lt;strong&gt;属于一个&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore.maps&lt;/code&gt; → 一个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; &lt;strong&gt;管理多个&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore.fileStore&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; &lt;strong&gt;持有一个&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mvstore.FileStore&lt;/code&gt; 做底层 I/O&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore.meta&lt;/code&gt; → 特殊的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&amp;lt;String,String&amp;gt;&lt;/code&gt; 记录所有 map 的元信息&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVTable.store&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVTable&lt;/code&gt; &lt;strong&gt;持有&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionStore&lt;/code&gt;，后者包装 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-pagestore-栈&quot;&gt;② PageStore 栈&lt;/h3&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// RegularTable 的索引持有 PageStore&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PageDataIndex&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Index&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;PageStore&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;store&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PageStore&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;FileStore&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;file&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// store.FileStore，与 mvstore.FileStore 不同&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// Database 整库共享一个 PageStore 实例&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Database&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;PageStore&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pageStore&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

核心关系：

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RegularTable&lt;/code&gt; 的索引（&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageDataIndex&lt;/code&gt;、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageBtreeIndex&lt;/code&gt;）&lt;strong&gt;持有&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore.file&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt; &lt;strong&gt;持有一个&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;store.FileStore&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Database.pageStore&lt;/code&gt; → 整库&lt;strong&gt;共享一个&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt; 实例&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;平行对应关系&quot;&gt;平行对应关系&lt;/h2&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;graph LR
    subgraph L1[&quot;表层&quot;]
        A1[&quot;RegularTable&quot;]
        B1[&quot;MVTable&quot;]
    end
    subgraph L2[&quot;事务层&quot;]
        B2[&quot;TransactionStore&quot;]
    end
    subgraph L3[&quot;存储引擎层&quot;]
        A3[&quot;PageStore&quot;]
        B3[&quot;MVStore&quot;]
    end
    subgraph L4[&quot;逻辑数据结构层&quot;]
        A4[&quot;store.Page 固定页 B-Tree&quot;]
        B4[&quot;MVMap + mvstore.Page&quot;]
    end
    subgraph L5[&quot;文件 I/O 层&quot;]
        A5[&quot;store.FileStore&quot;]
        B5[&quot;mvstore.FileStore&quot;]
    end

    A1 --&amp;gt; A3 --&amp;gt; A4 --&amp;gt; A5
    B1 --&amp;gt; B2 --&amp;gt; B3 --&amp;gt; B4 --&amp;gt; B5
&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id=&quot;-表层&quot;&gt;① 表层&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RegularTable&lt;/code&gt; vs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVTable&lt;/code&gt;：均继承 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TableBase&lt;/code&gt;，对应传统表与 MVCC 表。&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-事务层&quot;&gt;② 事务层&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVTable&lt;/code&gt; 通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionStore&lt;/code&gt; 支持 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVCC&lt;/code&gt;；&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RegularTable&lt;/code&gt; 直接耦合在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt; 中，没有独立事务层。&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-存储引擎层&quot;&gt;③ 存储引擎层&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; 是两套核心引擎，分别服务各自的上层表。&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-逻辑数据结构层&quot;&gt;④ 逻辑数据结构层&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt; 侧使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;store.Page&lt;/code&gt; 固定页 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B-Tree&lt;/code&gt;；&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; 侧使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt;（有序 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-V&lt;/code&gt; 树），内部节点为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mvstore.Page&lt;/code&gt;。&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-文件-io-层&quot;&gt;⑤ 文件 I/O 层&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;store.FileStore&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mvstore.FileStore&lt;/code&gt; 同名不同类，各自只服务本栈。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;核心差异总结&quot;&gt;核心差异总结&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;维度&lt;/th&gt;
      &lt;th&gt;MVStore 栈&lt;/th&gt;
      &lt;th&gt;PageStore 栈&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;默认启用&lt;/td&gt;
      &lt;td&gt;✔ 默认&lt;/td&gt;
      &lt;td&gt;❌ 需显式配置&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;事务支持&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVCC&lt;/code&gt; 多版本并发&lt;/td&gt;
      &lt;td&gt;默认传统锁机制（也可开启 MVCC）&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;中间层&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt;（多 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-V&lt;/code&gt; 树容器）&lt;/td&gt;
      &lt;td&gt;无，直接用固定页 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B-Tree&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;文件 I/O&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mvstore.FileStore&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;store.FileStore&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;表实现&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVTable&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RegularTable&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

🎈 &lt;strong&gt;最关键的区别&lt;/strong&gt;：&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt; 是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; 独有的中间层。&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; 是“多个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt; 的容器”，每张 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVTable&lt;/code&gt; 的数据/索引就是若干 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt;；&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PageStore&lt;/code&gt; 侧没有这层，直接用固定页 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B-Tree&lt;/code&gt; 索引。

🎈 RegularTable 有完整的 MVCC 事务语义，包括读己之写、隐藏其他事务未提交数据、写写冲突检测、提交与回滚；只是底层仍&lt;strong&gt;受 PageStore 全局同步&lt;/strong&gt;与内存 undoLog 的限制，不如 MVTable 的 MVStore 原生 MVCC。

&lt;h2 id=&quot;总结&quot;&gt;总结&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;PageStore（传统） 栈：&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RegularTable→PageStore→store.FileStore&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;MVStore 栈实现：&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVTable→(TransactionStore)→MVStore→mvstore.FileStore&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVMap&lt;/code&gt; 是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVStore&lt;/code&gt; 独有的中间层，理解这点就能区分两套引擎的核心设计差异&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FileStore&lt;/code&gt; 同名不同类，各自只服务本栈，是最底层的文件读写封装&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Fri, 03 Jul 2026 07:00:00 +0000</pubDate>
        <link>https://mrrobot5.github.io/2026/07/03/h2-mvstore-vs-regular-storage/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2026/07/03/h2-mvstore-vs-regular-storage/</guid>
        
        <category>H2数据库</category>
        
        <category>MVStore</category>
        
        <category>存储引擎</category>
        
        
        <category>源码阅读</category>
        
      </item>
    
      <item>
        <title>事务与消息发送同步方案</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#问题场景&quot; id=&quot;markdown-toc-问题场景&quot;&gt;问题场景&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#异常时序&quot; id=&quot;markdown-toc-异常时序&quot;&gt;异常时序&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#问题本质&quot; id=&quot;markdown-toc-问题本质&quot;&gt;问题本质&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#核心方案transactionsynchronizationadapter&quot; id=&quot;markdown-toc-核心方案transactionsynchronizationadapter&quot;&gt;核心方案：TransactionSynchronizationAdapter&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#方案设计&quot; id=&quot;markdown-toc-方案设计&quot;&gt;方案设计&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#执行时序&quot; id=&quot;markdown-toc-执行时序&quot;&gt;执行时序&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#优点与局限&quot; id=&quot;markdown-toc-优点与局限&quot;&gt;优点与局限&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#扩展场景缓存更新和事务一致性&quot; id=&quot;markdown-toc-扩展场景缓存更新和事务一致性&quot;&gt;扩展场景：缓存更新和事务一致性&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#背景缓存与事务的脏数据问题&quot; id=&quot;markdown-toc-背景缓存与事务的脏数据问题&quot;&gt;背景：缓存与事务的脏数据问题&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#transactionawarecachemanagerproxy-的设计&quot; id=&quot;markdown-toc-transactionawarecachemanagerproxy-的设计&quot;&gt;TransactionAwareCacheManagerProxy 的设计&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#其他同步方案&quot; id=&quot;markdown-toc-其他同步方案&quot;&gt;其他同步方案&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#总结&quot; id=&quot;markdown-toc-总结&quot;&gt;总结&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  业务操作复杂后，发送 MQ 消息和数据库事务往往存在时序错位。事务尚未提交，消息已被消费者处理，导致数据查询失败。

  本文的核心对象是 Spring 的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationAdapter&lt;/code&gt;，通过注册事务提交回调，以最小代价实现”事务成功后才发送消息”的同步保障。

  关键结论：&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronization&lt;/code&gt; 是单体应用内解决事务与外部交互一致性的轻量级方案，但若涉及主从延迟或网络延迟，则需要更复杂的分布式改造。
&lt;/blockquote&gt;

&lt;h2 id=&quot;问题场景&quot;&gt;问题场景&lt;/h2&gt;

&lt;h3 id=&quot;异常时序&quot;&gt;异常时序&lt;/h3&gt;

当业务操作（如创建订单、异常单）和发送 MQ 任务消息&lt;strong&gt;在同一事务中&lt;/strong&gt;执行时，如果在事务提交前就发送消息，消息消费者可能立即处理并查询数据库，此时事务还未提交，导致数据不一致。

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 问题代码示意：事务与消息发送时序错误
 */&lt;/span&gt;
&lt;span class=&quot;nd&quot;&gt;@Transactional&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;createOrder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Order&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;order&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;orderMapper&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;insert&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;order&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;// 1. 数据库操作&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mqProducer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;send&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orderMessage&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;// 2. 事务未提交，消息已发送 ❌&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 3. 其他耗时操作（业务逻辑、外部调用等）。消息消费者查询不到新增的数据 ❌&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 4. 事务提交在此之后&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🙉 消费者收到消息后查询数据库，可能查不到刚插入的数据——因为事务还未提交。

&lt;h3 id=&quot;问题本质&quot;&gt;问题本质&lt;/h3&gt;

核心矛盾在于&lt;strong&gt;事务边界与外部交互边界的错位&lt;/strong&gt;：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;阶段&lt;/th&gt;
      &lt;th&gt;消息发送时机&lt;/th&gt;
      &lt;th&gt;消费者查询结果&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;事务提交前发消息&lt;/td&gt;
      &lt;td&gt;消息已发送，但数据未提交&lt;/td&gt;
      &lt;td&gt;❌ 查不到数据&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;事务提交后发消息&lt;/td&gt;
      &lt;td&gt;数据已提交，消息后发送&lt;/td&gt;
      &lt;td&gt;✅ 正常查询&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

🎈 在单体应用、同库事务场景下，理想的方案是：让消息发送这个”外部交互”延迟到事务真正提交之后。

&lt;h2 id=&quot;核心方案transactionsynchronizationadapter&quot;&gt;核心方案：TransactionSynchronizationAdapter&lt;/h2&gt;

&lt;h3 id=&quot;方案设计&quot;&gt;方案设计&lt;/h3&gt;

Spring 提供了 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronization&lt;/code&gt; 接口，允许将自定义逻辑注册到事务生命周期中。其中 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 回调会在事务成功提交后触发，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCompletion()&lt;/code&gt; 则在事务完成（无论成功或失败）后触发。

🎈 选择 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit()&lt;/code&gt; 而非 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCompletion()&lt;/code&gt; 的原因是：只有事务成功提交后才需要发送消息；事务回滚时，数据未落库，不应发送消息。

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 事务提交后才发送 MQ 消息
 * @see org.springframework.transaction.support.TransactionSynchronizationAdapter
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MQTaskMessageBaseDto&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sendMQTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;TransactionSynchronizationManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;isSynchronizationActive&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;info&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;sendMQTask--事务提交后再发送消息:{}&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 注册事务同步回调，延迟到事务提交后执行&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;TransactionSynchronizationManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;registerSynchronization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;TransactionSynchronizationAdapter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;nd&quot;&gt;@Override&lt;/span&gt;
                    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;afterCommit&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                        &lt;span class=&quot;n&quot;&gt;doSendMQTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 事务已提交，安全发送&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;});&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;info&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;sendMQTask--直接发送消息:{}&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;doSendMQTask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;messageBody&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 无事务上下文，直接发送&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;执行时序&quot;&gt;执行时序&lt;/h3&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
    participant 业务服务
    participant 数据库
    participant MQ消息队列

    业务服务-&amp;gt;&amp;gt;数据库: 1. 开启事务
    业务服务-&amp;gt;&amp;gt;数据库: 2. 执行数据库操作
    业务服务-&amp;gt;&amp;gt;业务服务: 3. registerSynchronization&amp;lt;br/&amp;gt;(afterCommit 回调)
    业务服务-&amp;gt;&amp;gt;业务服务: 4. 其他耗时操作&amp;lt;br/&amp;gt;(业务逻辑、外部调用等)
    业务服务-&amp;gt;&amp;gt;数据库: 5. 提交事务
    数据库--&amp;gt;&amp;gt;业务服务: 6. 事务提交成功
    业务服务-&amp;gt;&amp;gt;MQ消息队列: 7. afterCommit() 触发&amp;lt;br/&amp;gt;发送 MQ 任务消息

    Note over MQ消息队列: ✅ 消息发送时数据已提交
&lt;/code&gt;&lt;/pre&gt;

✔ 这种方案的优势在于&lt;strong&gt;零侵入&lt;/strong&gt;——业务代码不需要关心事务状态，统一封装在消息发送层。

&lt;h3 id=&quot;优点与局限&quot;&gt;优点与局限&lt;/h3&gt;

⭐ 优点：复杂度低，Spring 原生支持; 实现难度低，代码量少

🎈 不足：如果涉及&lt;strong&gt;主从延迟&lt;/strong&gt;（消息发送后消费者读从库，数据尚未同步）或&lt;strong&gt;网络延迟&lt;/strong&gt;（消息先于事务提交传播到消费者），则需要更复杂的分布式改造方案（如本地消息表、事务消息等）。

&lt;h2 id=&quot;扩展场景缓存更新和事务一致性&quot;&gt;扩展场景：缓存更新和事务一致性&lt;/h2&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationAdapter&lt;/code&gt; 的应用不仅限于 MQ 消息发送。Spring Cache 模块中，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheManagerProxy&lt;/code&gt; 正是基于同样的思想，为缓存操作添加事务感知能力。

&lt;h3 id=&quot;背景缓存与事务的脏数据问题&quot;&gt;背景：缓存与事务的脏数据问题&lt;/h3&gt;

某些缓存管理器（如 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SimpleCacheManager&lt;/code&gt;）不支持直接的事务感知。如果在事务中先更新缓存、后回滚事务，缓存中就会残留脏数据：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@Transactional&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;updateData&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Data&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;put&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;// 1. 缓存已更新&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dataMapper&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;update&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;// 2. 数据库操作&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 3. 抛出异常，事务回滚&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 结果：缓存是新数据，数据库是旧数据 ❌&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;transactionawarecachemanagerproxy-的设计&quot;&gt;TransactionAwareCacheManagerProxy 的设计&lt;/h3&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheManagerProxy&lt;/code&gt; 基于&lt;strong&gt;组合模式&lt;/strong&gt;，为不支持事务感知的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CacheManager&lt;/code&gt; 添加事务同步能力。它本质上是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheDecorator&lt;/code&gt; 装饰目标 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cache&lt;/code&gt; 实例，将缓存写操作与 Spring 管理的事务绑定。

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 事务感知缓存装饰器
 * @see org.springframework.cache.transaction.TransactionAwareCacheDecorator
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransactionAwareCacheDecorator&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;implements&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Cache&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targetCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;nd&quot;&gt;@Override&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;put&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;TransactionSynchronizationManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;isSynchronizationActive&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// 存在活动事务时，延迟缓存写操作到事务提交后&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;TransactionSynchronizationManager&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;registerSynchronization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;TransactionSynchronizationAdapter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;nd&quot;&gt;@Override&lt;/span&gt;
                    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;afterCommit&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                        &lt;span class=&quot;n&quot;&gt;targetCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;put&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 事务提交后真正写入缓存&lt;/span&gt;
                    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
                &lt;span class=&quot;o&quot;&gt;});&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;targetCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;put&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 无事务，直接写入&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// evict、clear 等操作同理延迟执行&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🎈 核心逻辑与 MQ 发送方案完全一致：存在活动事务时，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;put&lt;/code&gt;、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;evict&lt;/code&gt;、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clear&lt;/code&gt; 等操作被注册到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationManager&lt;/code&gt;，延迟到事务成功提交后才真正执行。若事务回滚，这些缓存操作自然失效，不会污染缓存。

✔ 这种装饰器模式的设计非常优雅：&lt;strong&gt;不修改原有缓存管理器的实现&lt;/strong&gt;，仅通过代理层增强事务感知能力，符合开闭原则。

&lt;h2 id=&quot;其他同步方案&quot;&gt;其他同步方案&lt;/h2&gt;

在分布式场景或更高可靠性要求下，还有以下方案可供选择：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;方案&lt;/th&gt;
      &lt;th&gt;复杂度&lt;/th&gt;
      &lt;th&gt;可靠性&lt;/th&gt;
      &lt;th&gt;实现难度&lt;/th&gt;
      &lt;th&gt;适用场景&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;本地消息表&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;⭐⭐⭐&lt;/td&gt;
      &lt;td&gt;高&lt;/td&gt;
      &lt;td&gt;中&lt;/td&gt;
      &lt;td&gt;跨服务 / 跨库场景，需持久化消息&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;RocketMQ 事务消息&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;⭐⭐⭐&lt;/td&gt;
      &lt;td&gt;高&lt;/td&gt;
      &lt;td&gt;中&lt;/td&gt;
      &lt;td&gt;已使用 RocketMQ，两阶段提交&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;定时扫描补偿&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;⭐⭐&lt;/td&gt;
      &lt;td&gt;中&lt;/td&gt;
      &lt;td&gt;低&lt;/td&gt;
      &lt;td&gt;简单场景，允许最终一致性延迟&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Seata 分布式事务&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;⭐⭐⭐⭐&lt;/td&gt;
      &lt;td&gt;高&lt;/td&gt;
      &lt;td&gt;高&lt;/td&gt;
      &lt;td&gt;强一致性要求，改造代价大&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

🎈 选型建议：单体应用优先使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronization&lt;/code&gt;（本文方案）；跨服务、跨库场景考虑本地消息表或 RocketMQ 事务消息；对一致性要求极高且可接受高改造成本时，再考虑分布式事务框架。

&lt;h2 id=&quot;总结&quot;&gt;总结&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionSynchronizationAdapter&lt;/code&gt; 是 Spring 原生的事务生命周期钩子，以最小代码量实现”事务提交后执行外部操作”的同步保障。&lt;/li&gt;
  &lt;li&gt;核心模式是&lt;strong&gt;延迟执行&lt;/strong&gt;：将非事务性操作（MQ 发送、缓存更新）注册为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;afterCommit&lt;/code&gt; 回调，绑定到事务成功提交后才真正执行。&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionAwareCacheManagerProxy&lt;/code&gt; 是同一思想的经典应用，通过装饰器模式为缓存添加事务感知，避免事务回滚后的脏数据问题。&lt;/li&gt;
  &lt;li&gt;该方案适用于&lt;strong&gt;单体应用 / 同库事务&lt;/strong&gt;场景，实现简单、无额外依赖；若存在主从延迟、网络延迟或跨服务分布式场景，则需升级为本地消息表、事务消息等更复杂的方案。&lt;/li&gt;
  &lt;li&gt;技术选型的原则：在满足可靠性要求的前提下，优先选择&lt;strong&gt;复杂度最低&lt;/strong&gt;的方案。⭐&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Thu, 02 Jul 2026 09:03:00 +0000</pubDate>
        <link>https://mrrobot5.github.io/2026/07/02/transaction-synchronization-mq-sync/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2026/07/02/transaction-synchronization-mq-sync/</guid>
        
        <category>Spring</category>
        
        <category>事务控制</category>
        
        <category>MQ</category>
        
        
        <category>实战问题</category>
        
      </item>
    
      <item>
        <title>node-sass 兼容问题与 webpack loader 的巧妙设计</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#异常场景&quot; id=&quot;markdown-toc-异常场景&quot;&gt;异常场景&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#工程配置&quot; id=&quot;markdown-toc-工程配置&quot;&gt;工程配置&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#异常表现&quot; id=&quot;markdown-toc-异常表现&quot;&gt;异常表现&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#场景复现&quot; id=&quot;markdown-toc-场景复现&quot;&gt;场景复现&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#-node-sass-安装失败&quot; id=&quot;markdown-toc--node-sass-安装失败&quot;&gt;① node-sass 安装失败&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-dart-sass-编译报错&quot; id=&quot;markdown-toc--dart-sass-编译报错&quot;&gt;② dart-sass 编译报错&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#问题分析&quot; id=&quot;markdown-toc-问题分析&quot;&gt;问题分析&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#node-sass-的架构绑定&quot; id=&quot;markdown-toc-node-sass-的架构绑定&quot;&gt;node-sass 的架构绑定&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#deep-的废弃历程&quot; id=&quot;markdown-toc-deep-的废弃历程&quot;&gt;/deep/ 的废弃历程&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#解决方案&quot; id=&quot;markdown-toc-解决方案&quot;&gt;解决方案&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#-替换为-dart-sass&quot; id=&quot;markdown-toc--替换为-dart-sass&quot;&gt;① 替换为 dart-sass&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-string-replace-loader-配置&quot; id=&quot;markdown-toc--string-replace-loader-配置&quot;&gt;② string-replace-loader 配置&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-loader-顺序验证&quot; id=&quot;markdown-toc--loader-顺序验证&quot;&gt;③ loader 顺序验证&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#扩展webpack-loader-的设计思想&quot; id=&quot;markdown-toc-扩展webpack-loader-的设计思想&quot;&gt;扩展：webpack loader 的设计思想&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#-链式调用与从右到左执行&quot; id=&quot;markdown-toc--链式调用与从右到左执行&quot;&gt;① 链式调用与从右到左执行&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-单一职责与管道模式&quot; id=&quot;markdown-toc--单一职责与管道模式&quot;&gt;② 单一职责与管道模式&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#-loader-的本质内容转换函数&quot; id=&quot;markdown-toc--loader-的本质内容转换函数&quot;&gt;③ loader 的本质：内容转换函数&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#总结&quot; id=&quot;markdown-toc-总结&quot;&gt;总结&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  在维护一个老前端工程时，本地 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;npm run dev&lt;/code&gt; 突然无法启动。追根溯源，发现是 &lt;strong&gt;node-sass@6.0.1&lt;/strong&gt; 在 Apple Silicon (M1/M2) 架构上报错。替换为 dart-sass 后，又因为代码中使用了已被废弃的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt; 深度选择器语法而编译失败。

  目标很明确：❌ 不修改已有工程的源码和配置，通过 webpack loader 的巧妙编排，实现本地服务的无痛启动。

  最终方案是：在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sass-loader&lt;/code&gt; 之后注入 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string-replace-loader&lt;/code&gt;，将 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt; 替换为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;::v-deep&lt;/code&gt;，并借此机会深入理解 webpack loader 的设计哲学。
&lt;/blockquote&gt;

&lt;h2 id=&quot;异常场景&quot;&gt;异常场景&lt;/h2&gt;

&lt;h3 id=&quot;工程配置&quot;&gt;工程配置&lt;/h3&gt;

该工程是一个基于 Vue 2.x 的老项目，构建工具使用 webpack 4，样式处理器配置如下：

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// webpack.config.js 片段&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;nl&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sr&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\.&lt;/span&gt;&lt;span class=&quot;sr&quot;&gt;scss$/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;nx&quot;&gt;use&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
    &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;vue-style-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;css-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;sass-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 内部依赖 node-sass&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-json highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;err&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;package.json&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;err&quot;&gt;片段&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;dependencies&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;node-sass&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;^6.0.1&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;异常表现&quot;&gt;异常表现&lt;/h3&gt;

在新的 MacBook Pro (M1 Pro, arm64) 上执行 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;npm install&lt;/code&gt; 时，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;node-sass&lt;/code&gt; 安装阶段直接报错：

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Error: Node Sass does not yet support your current environment: OS X Unsupported architecture (arm64)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🙉 错误信息非常直接：当前操作系统架构为 arm64，而 node-sass@6.0.1 的预编译二进制包仅支持 x64。这是一个&lt;strong&gt;架构级别的硬兼容性问题&lt;/strong&gt;，无法通过简单的降级或升级 Node.js 版本解决。

&lt;h2 id=&quot;场景复现&quot;&gt;场景复现&lt;/h2&gt;

&lt;h3 id=&quot;-node-sass-安装失败&quot;&gt;① node-sass 安装失败&lt;/h3&gt;

node-sass 是一个 Node.js 到 libsass 的绑定库，libsass 使用 C++ 编写。发布时，node-sass 会针对特定平台（OS + 架构 + Node 版本）提供预编译的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.node&lt;/code&gt; 二进制文件。

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Downloading binary from https://github.com/sass/node-sass/releases/download/v6.0.1/
darwin-arm64-83_binding.node
Cannot download &quot;https://github.com/sass/node-sass/releases/download/v6.0.1/darwin-arm64-83_binding.node&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

❌ 查看 &lt;a href=&quot;https://github.com/sass/node-sass/releases&quot;&gt;node-sass release 页面&lt;/a&gt;，v6.0.1 的 release assets 中仅有 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;darwin-x64&lt;/code&gt; 包，没有 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;darwin-arm64&lt;/code&gt;。

&lt;h3 id=&quot;-dart-sass-编译报错&quot;&gt;② dart-sass 编译报错&lt;/h3&gt;

既然 node-sass 不支持 arm64，自然的替代方案是使用 &lt;strong&gt;dart-sass&lt;/strong&gt;（即 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sass&lt;/code&gt; 包）。dart-sass 是 Sass 的官方实现，纯 JavaScript/ Dart 编译，没有原生依赖，跨平台支持极好。

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;npm uninstall node-sass
npm &lt;span class=&quot;nb&quot;&gt;install &lt;/span&gt;sass &lt;span class=&quot;nt&quot;&gt;--save-dev&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

然而项目启动后，编译阶段报错：

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;SassError: expected selector.
/deep/ .some-class
^
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

❌ 原因是：工程源码中大量使用了 Vue 的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt; 深度选择器语法，而 &lt;strong&gt;dart-sass 2.0+ 已完全废弃 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt;，仅支持 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;::v-deep&lt;/code&gt;&lt;/strong&gt;。这导致大量的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.scss&lt;/code&gt; 文件无法通过编译。

&lt;h2 id=&quot;问题分析&quot;&gt;问题分析&lt;/h2&gt;

&lt;h3 id=&quot;node-sass-的架构绑定&quot;&gt;node-sass 的架构绑定&lt;/h3&gt;

node-sass 的核心问题在于其&lt;strong&gt;强平台绑定&lt;/strong&gt;的设计。它依赖 libsass（C++ 库），必须通过 node-gyp 编译或在发布时提供预编译二进制文件。这种架构在平台迁移期（如 x86_64 → arm64）会暴露严重的兼容性缺陷：

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;node-sass → libsass (C++) → 平台特定二进制 → 强绑定 OS + CPU 架构 + Node ABI 版本
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🎈 相比之下，dart-sass 是 Sass 官方推荐的实现，使用 Dart 编译为 JavaScript（或原生可执行文件），完全脱离平台二进制依赖，是未来趋势。node-sass 本身也已于 2020 年被官方标记为废弃（deprecated）。

&lt;h3 id=&quot;deep-的废弃历程&quot;&gt;/deep/ 的废弃历程&lt;/h3&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt; 原本是 CSS Shadow DOM 规范中的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt; 选择器的别名，Vue 在 scoped CSS 中借用它来实现样式穿透。但 CSS 工作组已废弃 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt;，Sass 编译器随之跟进：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;版本&lt;/th&gt;
      &lt;th&gt;行为&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;libsass (node-sass)&lt;/td&gt;
      &lt;td&gt;仍支持 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt; 作为普通选择器&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;dart-sass &amp;lt; 1.23&lt;/td&gt;
      &lt;td&gt;支持，但发出 deprecation warning&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;dart-sass ≥ 2.0&lt;/td&gt;
      &lt;td&gt;❌ 完全废弃，编译报错&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

🎈 问题的矛盾点在于：&lt;strong&gt;源码是旧的，但构建工具必须升级&lt;/strong&gt;。修改所有源码中的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt; 为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;::v-deep&lt;/code&gt; 虽然可行，但会引入大量无意义的 diff，且可能触发其他老浏览器兼容问题。最好的方案是在编译阶段做”兼容转换”。

&lt;h2 id=&quot;解决方案&quot;&gt;解决方案&lt;/h2&gt;

&lt;h3 id=&quot;-替换为-dart-sass&quot;&gt;① 替换为 dart-sass&lt;/h3&gt;

首先，卸载 node-sass，安装 dart-sass：

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;npm uninstall node-sass
npm &lt;span class=&quot;nb&quot;&gt;install &lt;/span&gt;sass &lt;span class=&quot;nt&quot;&gt;--save-dev&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

✔ 此时 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sass-loader&lt;/code&gt; 会自动探测并使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sass&lt;/code&gt; 包（dart-sass），无需修改 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webpack.config.js&lt;/code&gt; 中的 loader 名称。

&lt;h3 id=&quot;-string-replace-loader-配置&quot;&gt;② string-replace-loader 配置&lt;/h3&gt;

接下来，引入 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string-replace-loader&lt;/code&gt;，在 sass 编译之前（从源码角度看，是 loader 链的右侧）将 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt; 替换为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;::v-deep&lt;/code&gt;：

&lt;div class=&quot;language-bash highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;npm &lt;span class=&quot;nb&quot;&gt;install &lt;/span&gt;string-replace-loader &lt;span class=&quot;nt&quot;&gt;--save-dev&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// webpack.config.js 修改后&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;nl&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sr&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\.&lt;/span&gt;&lt;span class=&quot;sr&quot;&gt;scss$/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;nx&quot;&gt;use&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
    &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;vue-style-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;css-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;sass-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 可根据需要配置 additionalData 等&lt;/span&gt;
      &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;string-replace-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;na&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;na&quot;&gt;search&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;/deep/&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;na&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;::v-deep&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;na&quot;&gt;flags&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;g&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// 全局替换&lt;/span&gt;
      &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🎈 关键点：webpack loader 的&lt;strong&gt;执行顺序是从右到左，从下到上&lt;/strong&gt;。数组右侧的 loader 先执行，处理最原始的源码；处理后的结果向左传递。因此将 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string-replace-loader&lt;/code&gt; 放在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sass-loader&lt;/code&gt; 的&lt;strong&gt;右侧（即数组中的下方/后面）&lt;/strong&gt;，它会在 sass 编译之前先执行文本替换。

&lt;blockquote&gt;
  另一种等价的配置方式（使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;enforce: &apos;post&apos;&lt;/code&gt; 或 webpack chain 的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;after&lt;/code&gt;）：
  &lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// vue.config.js 中使用 webpack-chain&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;config&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;module&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;rule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;scss&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;use&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;string-replace-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;string-replace-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;after&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;sass-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 确保在 sass-loader 之后执行（数组右侧）&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;search&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;/deep/&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;::v-deep&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;flags&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;g&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;  &lt;/div&gt;
  &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;after(&apos;sass-loader&apos;)&lt;/code&gt; 会将 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string-replace-loader&lt;/code&gt; 插入到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sass-loader&lt;/code&gt; 的后面（数组的右侧），符合从右到左的执行顺序。
&lt;/blockquote&gt;

&lt;h3 id=&quot;-loader-顺序验证&quot;&gt;③ loader 顺序验证&lt;/h3&gt;

为了验证 loader 的调用顺序，可以通过以下方式确认：

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// 自定义一个 debug loader 验证执行顺序&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;debugLoader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;string-replace-loader&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;search&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;/deep/&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;::v-deep&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;flags&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;g&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// 执行顺序：string-replace-loader → sass-loader → css-loader → vue-style-loader&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 即：先替换文本，再编译 sass，再处理 css，最后注入样式&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

✔ 验证通过后，工程可以正常启动，所有 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt; 语法在编译阶段被静默替换，源码无需任何改动。

&lt;h2 id=&quot;扩展webpack-loader-的设计思想&quot;&gt;扩展：webpack loader 的设计思想&lt;/h2&gt;

本次问题能够优雅解决，核心得益于 webpack loader 的精妙设计。下面从三个维度展开分析。

&lt;h3 id=&quot;-链式调用与从右到左执行&quot;&gt;① 链式调用与从右到左执行&lt;/h3&gt;

webpack loader 的配置是一个数组，但执行顺序并非直觉上的从左到右，而是&lt;strong&gt;从右到左，从后往前&lt;/strong&gt;：

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;use: [A, B, C]
执行顺序：C → B → A
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🎈 这种设计暗合了&lt;strong&gt;函数组合（Function Composition）&lt;/strong&gt;的数学直觉。如果每个 loader 是一个函数 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;f(resource)&lt;/code&gt;，那么整个 loader 链等价于：

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;source&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

即最右侧的 loader 先接触原始资源，经过层层转换后，最左侧的 loader 输出最终结果给 webpack 的模块系统。这种设计使得：

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;源码预处理&lt;/strong&gt;（如替换、转译）放在右侧，先执行；&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;后处理&lt;/strong&gt;（如样式注入、资源打包）放在左侧，最后执行。&lt;/li&gt;
&lt;/ul&gt;

本案例中的 loader 执行顺序如下：

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;graph LR
    A[原始源码] --&amp;gt; B[string-replace-loader]
    B --&amp;gt; C[sass-loader]
    C --&amp;gt; D[css-loader]
    D --&amp;gt; E[vue-style-loader]
    E --&amp;gt; F[最终输出]

    style B fill:#e1f5fe,stroke:#01579b
    style C fill:#e1f5fe,stroke:#01579b
    style D fill:#e1f5fe,stroke:#01579b
    style E fill:#e1f5fe,stroke:#01579b
&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id=&quot;-单一职责与管道模式&quot;&gt;② 单一职责与管道模式&lt;/h3&gt;

每个 loader 只负责一种转换，这是&lt;strong&gt;单一职责原则（SRP）&lt;/strong&gt;的典型实践：

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Loader&lt;/th&gt;
      &lt;th&gt;职责&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string-replace-loader&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;纯文本替换，不解析 AST&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sass-loader&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;将 Sass/SCSS 编译为 CSS&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;css-loader&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;解析 CSS 中的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@import&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;url()&lt;/code&gt;，处理模块化&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vue-style-loader&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;将 CSS 注入 DOM 的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;style&amp;gt;&lt;/code&gt; 标签&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

🎈 这种管道模式（Pipeline Pattern）的好处是：loader 之间&lt;strong&gt;完全解耦&lt;/strong&gt;。&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string-replace-loader&lt;/code&gt; 不需要知道 Sass 语法，只需要按字符串规则替换；&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sass-loader&lt;/code&gt; 也不需要关心源码中是否包含 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/deep/&lt;/code&gt;，它只负责编译标准的 SCSS。每个组件专注做好一件事，通过标准接口（字符串输入 → 字符串输出）串联起来。

&lt;h3 id=&quot;-loader-的本质内容转换函数&quot;&gt;③ loader 的本质：内容转换函数&lt;/h3&gt;

从源码层面看，一个 loader 本质上是一个符合特定签名的 JavaScript 函数：

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * webpack loader 的标准接口
 * @see webpack/lib/NormalModuleLoaderContext.js
 * @param {string|Buffer} source 模块源码内容
 * @returns {string|Buffer} 转换后的内容
 */&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;exports&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;source&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;// 对 source 进行任意转换&lt;/span&gt;
  &lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;source&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//deep\//g, &apos;::v-deep&apos;);&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

🎈 这意味着 loader 拥有&lt;strong&gt;极大的灵活性&lt;/strong&gt;：

&lt;ul&gt;
  &lt;li&gt;它可以是无状态的纯函数（如 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string-replace-loader&lt;/code&gt;）；&lt;/li&gt;
  &lt;li&gt;也可以是有状态的（通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; 上下文访问 webpack 的 loader API）；&lt;/li&gt;
  &lt;li&gt;甚至可以是异步的（通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this.async()&lt;/code&gt; 回调）。&lt;/li&gt;
&lt;/ul&gt;

webpack 只关心输入输出契约，不关心内部实现，这正是 loader 生态能够蓬勃发展的根本原因。

&lt;h2 id=&quot;总结&quot;&gt;总结&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;node-sass 的 arm64 兼容问题&lt;/strong&gt;是原生绑定库的共性问题，dart-sass 作为纯 JS 实现是更现代的替代方案。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;不修改源码&lt;/strong&gt;的前提下，通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string-replace-loader&lt;/code&gt; 在编译阶段做语法兼容，是一种低侵入、可回滚的优雅方案。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;webpack loader 从右到左的执行顺序&lt;/strong&gt;是函数组合思想的工程体现，理解这一点是正确配置 loader 链的关键。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;单一职责 + 管道模式&lt;/strong&gt;使得 loader 生态高度解耦、可扩展，每个 loader 只需关注一种转换，通过编排解决复杂问题。&lt;/li&gt;
  &lt;li&gt;老工程的维护艺术往往不在于重写，而在于找到&lt;strong&gt;基础设施层面的兼容层&lt;/strong&gt;，让旧代码在新环境中继续稳定运行。⭐&lt;/li&gt;
&lt;/ul&gt;
</description>
        <pubDate>Wed, 24 Jun 2026 10:11:00 +0000</pubDate>
        <link>https://mrrobot5.github.io/2026/06/24/node-sass-compat-webpack-loader-design/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2026/06/24/node-sass-compat-webpack-loader-design/</guid>
        
        <category>Webpack</category>
        
        <category>Node.js</category>
        
        
        <category>实战问题</category>
        
      </item>
    
      <item>
        <title>类加载机制引起 Spring 属性解析异常分析</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#异常场景&quot; id=&quot;markdown-toc-异常场景&quot;&gt;异常场景&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#工程配置&quot; id=&quot;markdown-toc-工程配置&quot;&gt;工程配置&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#异常表现&quot; id=&quot;markdown-toc-异常表现&quot;&gt;异常表现&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#场景复现&quot; id=&quot;markdown-toc-场景复现&quot;&gt;场景复现&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#问题分析&quot; id=&quot;markdown-toc-问题分析&quot;&gt;问题分析&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  在使用 Idea 开发Spring 应用过程中，突然有一次应用启动报错：Could not resolve placeholder ‘mq.address’ in value “${mq.address}”

  由此开始此次的源码阅读和异常分析。

  最后追踪分析是 &lt;strong&gt;JRebel 类加载器的作用机制&lt;/strong&gt; 导致的异常。
&lt;/blockquote&gt;

&lt;h2 id=&quot;异常场景&quot;&gt;异常场景&lt;/h2&gt;

&lt;h3 id=&quot;工程配置&quot;&gt;工程配置&lt;/h3&gt;

Spring Boot 配置

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@ImportResource&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;({&lt;/span&gt;
        &lt;span class=&quot;s&quot;&gt;&quot;classpath:spring/spring-mq-producer.xml&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;s&quot;&gt;&quot;classpath:spring/spring-bean.xml&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;})&lt;/span&gt;
&lt;span class=&quot;nd&quot;&gt;@PropertySource&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;classpath:important.properties&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;encoding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;utf-8&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nd&quot;&gt;@Slf4j&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;WebApplication&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;extends&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SpringBootServletInitializer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

spring-bean.xml 文件配置

&lt;div class=&quot;language-xml highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c&quot;&gt;&amp;lt;!-- 以通配符的形式引入属性文件 --&amp;gt;&lt;/span&gt;
&lt;span class=&quot;nt&quot;&gt;&amp;lt;context:property-placeholder&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;location=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;classpath:*.properties&quot;&lt;/span&gt;&lt;span class=&quot;nt&quot;&gt;/&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;异常表现&quot;&gt;异常表现&lt;/h3&gt;

通过 @PropertySource 配置的属性可以解析并替换占位符✔

通过 context:property-placeholder 配置的属性解析不到，直接报错❌

&lt;h2 id=&quot;场景复现&quot;&gt;场景复现&lt;/h2&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// demo: resolver 查找类路径文件的过程。&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 问题复现：需要在当前工程中引入异常的jrebel.xml, 使用JRebel 启动。⭐&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;args&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;nc&quot;&gt;PathMatchingResourcePatternResolver&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;resolver&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PathMatchingResourcePatternResolver&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;

	&lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
		&lt;span class=&quot;c1&quot;&gt;// 查找类路径下的所有 *.properties 文件&lt;/span&gt;
		&lt;span class=&quot;nc&quot;&gt;Resource&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;resources&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;resolver&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getResources&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;classpath:*.properties&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
		&lt;span class=&quot;n&quot;&gt;printResources&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;classpath:*.properties&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;resources&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
	&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;IOException&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
		&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;printStackTrace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
	&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;问题分析&quot;&gt;问题分析&lt;/h2&gt;

根据相关源码，初步定位在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PropertySourcesPlaceholderConfigurer&lt;/code&gt; setLocations 初始化时，注入的文件是空的，导致无法成功引入属性文件。

进一步 debug 定位分析，发现 ClassLoader#getResource 过程中，classpath 路径不是当前工程的。

👉通过分析 classpath 相关jar,  发现依赖的 jar 包含 rebel.xml 文件。JRebel会根据&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rebel.xml&lt;/code&gt;配置文件中的 classpath 配置扫描指定的目录和 JAR 文件。

这样，查找文件不是当前工程目录(/workspace/another.foo.com/target/classes)，肯定找不到配置文件。

JRebel 类加载器与 Spring 属性解析的冲突流程如下：

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;graph TD
    A[Spring 启动] --&amp;gt; B[解析 context:property-placeholder]
    B --&amp;gt; C[PathMatchingResourcePatternResolver&amp;lt;br/&amp;gt;查找 classpath:*.properties]
    C --&amp;gt; D{ClassLoader 类型}
    D --&amp;gt;|正常 AppClassLoader| E[扫描当前工程 target/classes]
    D --&amp;gt;|JRebel 类加载器| F[扫描 rebel.xml 配置的目录]
    F --&amp;gt; G[路径指向 /workspace/another.foo.com&amp;lt;br/&amp;gt;❌ 非当前工程]
    G --&amp;gt; H[找不到 *.properties 文件]
    H --&amp;gt; I[PropertySourcesPlaceholderConfigurer&amp;lt;br/&amp;gt;locations 为空]
    I --&amp;gt; J[占位符解析失败&amp;lt;br/&amp;gt;Could not resolve placeholder]
    E --&amp;gt; K[正常加载属性文件]

    style D fill:#e1f5fe,stroke:#01579b
    style F fill:#fff3e0,stroke:#e65100
    style G fill:#ffebee,stroke:#c62828
    style J fill:#ffebee,stroke:#c62828
    style K fill:#e8f5e9,stroke:#2e7d32
&lt;/code&gt;&lt;/pre&gt;

&lt;img src=&quot;/images/find-the-jrebel.png&quot; alt=&quot;TransactionsEssentials&quot; style=&quot;zoom:50%;&quot; /&gt;

</description>
        <pubDate>Tue, 21 Jan 2025 14:49:20 +0000</pubDate>
        <link>https://mrrobot5.github.io/2025/01/21/Spring-properties-location-issue/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2025/01/21/Spring-properties-location-issue/</guid>
        
        <category>Spring</category>
        
        
        <category>源码阅读</category>
        
      </item>
    
      <item>
        <title>数据层中间件使用二三事</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#mybatis-一级缓存&quot; id=&quot;markdown-toc-mybatis-一级缓存&quot;&gt;Mybatis 一级缓存&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#问题场景&quot; id=&quot;markdown-toc-问题场景&quot;&gt;①问题场景&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#分析过程&quot; id=&quot;markdown-toc-分析过程&quot;&gt;②分析过程&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#相关知识&quot; id=&quot;markdown-toc-相关知识&quot;&gt;③相关知识&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#spring-事务嵌套&quot; id=&quot;markdown-toc-spring-事务嵌套&quot;&gt;Spring 事务嵌套&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#问题场景-1&quot; id=&quot;markdown-toc-问题场景-1&quot;&gt;①问题场景&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#分析过程-1&quot; id=&quot;markdown-toc-分析过程-1&quot;&gt;②分析过程&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#总结&quot; id=&quot;markdown-toc-总结&quot;&gt;③总结&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#dbcp-事务隔离级别失效&quot; id=&quot;markdown-toc-dbcp-事务隔离级别失效&quot;&gt;DBCP 事务隔离级别失效&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#问题场景-2&quot; id=&quot;markdown-toc-问题场景-2&quot;&gt;①问题场景&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#分析过程-2&quot; id=&quot;markdown-toc-分析过程-2&quot;&gt;②分析过程&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  近期在运维和改造旧系统的过程中，遇到了几个Mybatis 缓存、Spring 事务管理、数据库连接池影响事务隔离级别的问题。

  特此记录问题的场景和主要原因，方便后续避坑和查阅。
&lt;/blockquote&gt;

&lt;h2 id=&quot;mybatis-一级缓存&quot;&gt;Mybatis 一级缓存&lt;/h2&gt;

&lt;h3 id=&quot;问题场景&quot;&gt;①问题场景&lt;/h3&gt;

使用 Mybatis 从数据库中查询的数据，再次查询发现前后两次查询结果不一致。

问题场景的代码示例：

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;BlogMapper&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bMapper&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;session&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getMapper&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BlogMapper&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;class&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;Blog&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blog&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bMapper&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;selectBlog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;blog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;setName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;changed&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 再次查询相同的数据时，MyBatis 会直接从缓存中获取结果，而不再执行 SQL 语句。&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;Blog&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blog2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bMapper&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;selectBlog&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 打印结果：&quot;changed&quot;。 blog 和 blog2 为同一对象。🎈&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blog2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;分析过程&quot;&gt;②分析过程&lt;/h3&gt;

&lt;blockquote&gt;
  由于业务逻辑比较复杂，第一次查询的结果，在其他方法中对属性重新赋值。导致的现象比较奇怪。

  通过开启 debug日志，打印 Mybatis SQL, 第二次查询没有发起 SQL 请求（再次执行相同的 SQL 语句时，MyBatis 会直接从缓存中获取结果，而不再发送 SQL 请求到数据库）。

  Mybatis 使用了一级缓存。两次查询结果是同一对象。
&lt;/blockquote&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 一级缓存是 MyBatis 默认开启的缓存机制，它是基于 SqlSession 级别的缓存。
 * @see BaseExecutor#query(MappedStatement, Object, RowBounds, ResultHandler, CacheKey, BoundSql)
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;E&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;List&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;E&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;query&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MappedStatement&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ms&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RowBounds&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rowBounds&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResultHandler&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;resultHandler&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CacheKey&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BoundSql&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boundSql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SQLException&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// By default, flushCacheRequired is false for select statements&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;queryStack&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ms&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;isFlushCacheRequired&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;clearLocalCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 相同 SQL (CacheKey 一样)再次查询，直接从缓存中获取结果。&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;resultHandler&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;List&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;E&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;localCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getObject&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;handleLocallyCachedOutputParameters&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ms&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boundSql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// 发送 SQL 请求到数据库&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;queryFromDatabase&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ms&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rowBounds&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;resultHandler&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boundSql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;相关知识&quot;&gt;③相关知识&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;
    MyBatis 一级缓存（Local Cache）是 MyBatis 默认开启的缓存机制，它是基于 SqlSession 级别的缓存。
  &lt;/li&gt;
  &lt;li&gt;
    缓存失效场景：执行 SqlSession 的增删改操作（如 insert, update, delete），会清空一级缓存。
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;spring-事务嵌套&quot;&gt;Spring 事务嵌套&lt;/h2&gt;

&lt;h3 id=&quot;问题场景-1&quot;&gt;①问题场景&lt;/h3&gt;

为了解决&lt;strong&gt;大事务&lt;/strong&gt;更新过程中，多事务间数据不可见的问题。

在后置处理方法中开启新事务，调整事务隔离级别为 &lt;strong&gt;READ_UNCOMMITTED&lt;/strong&gt;。方便汇总计算逻辑可以及时共享数据。

带来的问题是： 有一定概率抛出异常 &lt;em&gt;CannotAcquireLockException&lt;/em&gt;

&lt;blockquote&gt;
  Error updating database.  Cause: java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
&lt;/blockquote&gt;

&lt;h3 id=&quot;分析过程-1&quot;&gt;②分析过程&lt;/h3&gt;

开启新事务，用的是 Spring事务管理 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;REQUIRES_NEW&lt;/code&gt; 传播行为。

将当前事务 A 挂起，创建一个新的事务 B。

事务 A 中发起某条数据的update, 尚未提交。事务 B 同样发起这条数据的 update, 导致超时锁等待异常。

参考数据库的锁机制： &lt;a href=&quot;./2023-10-08-Insight-h2database-update-execute-locks-transaction.md&quot;&gt;Insight h2database 更新、读写锁以及事务原理&lt;/a&gt;

&lt;h3 id=&quot;总结&quot;&gt;③总结&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;
    这个问题是个典型的资源竞争 &lt;strong&gt;(Resource Contention)&lt;/strong&gt;/死锁 &lt;strong&gt;(Deadlock)&lt;/strong&gt; 问题。
  &lt;/li&gt;
  &lt;li&gt;
    使用Spring 事务嵌套，需要特别注意更新数据的边界。尽量有充分的测试和验证，避免线上事故。
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;dbcp-事务隔离级别失效&quot;&gt;DBCP 事务隔离级别失效&lt;/h2&gt;

&lt;h3 id=&quot;问题场景-2&quot;&gt;①问题场景&lt;/h3&gt;

在Spring 事务管理中，通过配置 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Isolation.READ_UNCOMMITTED&lt;/code&gt; ，修改当前会话/数据库连接的事务隔离级别。

在测试验证中，其他事务更新过程中的数据，当前事务中 select 结果中没有。

也就是说，事务隔离级别并没有生效。

&lt;h3 id=&quot;分析过程-2&quot;&gt;②分析过程&lt;/h3&gt;

排查思路：使用 JdbcTemplate 以及原生 Jdbc API 开启事务隔离级别，把问题范围缩小并定位到数据库连接池组件（DBCP）上。

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 验证数据库连接的有效性
 * @param sql 如果sql参数是null或为空字符串，代码会调用连接的isValid(timeout)方法来检查连接是否有效。
 *            如果sql参数不为null，代码会执行这条SQL作为一个查询，并检查结果集（ResultSet）是否至少包含一行。
 * @see org.apache.commons.dbcp2.PoolableConnectionFactory#validateConnection
 * @see org.apache.commons.dbcp2.PoolableConnection#validate
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;validate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;timeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;throws&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SQLException&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sql&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// java.sql.Connection.isValid&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isValid&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;timeout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;SQLException&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;isValid() returned false&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(!&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;equals&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lastValidationSql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;lastValidationSql&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 此处创建了prepareStatement， 并缓存到当前 connection ❌&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;validationPreparedStatement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getInnermostDelegateInternal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;prepareStatement&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sql&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

👉DBCP validationQuery 事务隔离级别失效 Example. &lt;a href=&quot;https://github.com/MrRobot5/java-snippet/blob/main/jdbc/src/main/java/com/foo/example/TransactionIsolationExample.java&quot;&gt;TransactionIsolationExample&lt;/a&gt;

Spring 事务开启前、数据库连接池获取 Connection 之前，由于DBCP 已经创建了 prepareStatement， 导致后续再次设置事务隔离级别失效。

</description>
        <pubDate>Thu, 08 Aug 2024 09:50:00 +0000</pubDate>
        <link>https://mrrobot5.github.io/2024/08/08/Some-Stuff-DataAcess-Middleware/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2024/08/08/Some-Stuff-DataAcess-Middleware/</guid>
        
        <category>Spring</category>
        
        <category>DataSource</category>
        
        <category>Mybatis</category>
        
        <category>事务控制</category>
        
        
        <category>实战问题</category>
        
      </item>
    
      <item>
        <title>JQuery-data-设计分析</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#jquery-data&quot; id=&quot;markdown-toc-jquery-data&quot;&gt;JQuery Data&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#get-方法&quot; id=&quot;markdown-toc-get-方法&quot;&gt;①get 方法&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#-data-方法&quot; id=&quot;markdown-toc--data-方法&quot;&gt;② data 方法&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#-字符串类型转换&quot; id=&quot;markdown-toc--字符串类型转换&quot;&gt;③ 字符串类型转换&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#jquery-expando-设计&quot; id=&quot;markdown-toc-jquery-expando-设计&quot;&gt;JQuery expando 设计&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#简化示例&quot; id=&quot;markdown-toc-简化示例&quot;&gt;简化示例&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#设计分析&quot; id=&quot;markdown-toc-设计分析&quot;&gt;设计分析&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#数据隔离避免冲突&quot; id=&quot;markdown-toc-数据隔离避免冲突&quot;&gt;数据隔离/避免冲突&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#性能优化&quot; id=&quot;markdown-toc-性能优化&quot;&gt;性能优化&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  JQuery 的data 功能可以动态的存取数据，不用频繁的操作DOM。

  在事件处理程序之间传递数据非常有用。
&lt;/blockquote&gt;

&lt;h2 id=&quot;jquery-data&quot;&gt;JQuery Data&lt;/h2&gt;

&lt;blockquote&gt;
  JQuery 定义一个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Data&lt;/code&gt; 构造函数。默认实例化两个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Data&lt;/code&gt; 对象（dataUser、dataPriv）供功能使用。🎈

  数据的存取实现，就是通过 Data 来定义和实现。
&lt;/blockquote&gt;

&lt;h3 id=&quot;get-方法&quot;&gt;①get 方法&lt;/h3&gt;

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 每次实例化 Data 对象时，都会生成一个唯一的 expando 属性值。&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;expando&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;jQuery&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;expando&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;uid&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// 通过设置原型对象，定义 Data 实例共享的方法和属性。&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;Data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;cm&quot;&gt;/**
     * 数据获取
     * @param {*} owner 对应到 data功能，就是 Dom 对象
     * @param {*} key 可以为空, 如果不指定，获取 owner 绑定的所有数据。
     * @returns 
     */&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;owner&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// 类似于 owner[ this.expando ]&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;owner&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// 如果存在 expando 属性值，则返回 owner[ this.expando ][ camelCaseKey ] 的值&lt;/span&gt;
            &lt;span class=&quot;nx&quot;&gt;owner&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;expando&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;owner&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;expando&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;][&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;jQuery&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;camelCase&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;-data-方法&quot;&gt;② data 方法&lt;/h2&gt;

&lt;blockquote&gt;
  抽象定义和初始化 Data 对象后，使用dataUser 操作Dom 存取数据变的很方便。

  同时兼容了HTML5 data-* 特性，读取数据后类型转换并同步到 dataUser 中。
&lt;/blockquote&gt;

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 扩展 jQuery 实例方法，扩展后的方法可以在所有 jQuery 对象实例上调用。例如：$(&apos;p&apos;).data(&apos;someData&apos;);
 * 对比：jQuery.extend。用于扩展 jQuery 构造函数的静态方法或属性。$.data(elem, &apos;someData&apos;)
 */&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;jQuery&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;extend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;cm&quot;&gt;/**
     * 从dom 对象存取数据。value 有值是set 操作，无值是get 操作
     * @param {*} key 数据key
     * @param {*} value 允许为空
     * @returns 
     */&lt;/span&gt;
    &lt;span class=&quot;na&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;elem&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;access&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;

            &lt;span class=&quot;c1&quot;&gt;// get 操作&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;elem&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;dataUser&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;elem&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

                &lt;span class=&quot;c1&quot;&gt;// 兼容 HTML5 custom data-* attrs&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;// 如果获取到 data-* 字符串，会尝试进行类型转换，或者json 反序列化&lt;/span&gt;
                &lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;dataAttr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;elem&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
                &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

                &lt;span class=&quot;c1&quot;&gt;// We tried really hard, but the data doesn&apos;t exist.&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

            &lt;span class=&quot;c1&quot;&gt;// set 操作&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;each&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;nx&quot;&gt;dataUser&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;},&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;arguments&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;-字符串类型转换&quot;&gt;③ 字符串类型转换&lt;/h3&gt;

&lt;blockquote&gt;
  类型转换方便了取值后的操作，同时 JavaScript 类型的隐含转换也需要注意。🎈
&lt;/blockquote&gt;

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// 用于匹配一个完整的 JSON 对象或数组。&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 1. 以 `{` 开头，以 `}` 结尾，中间可以包含任意字符。&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 2. 以 `[` 开头，以 `]` 结尾，中间可以包含任意字符。&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;rbrace&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sr&quot;&gt;/^&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;(?:\{[\w\W]&lt;/span&gt;&lt;span class=&quot;sr&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\}&lt;/span&gt;&lt;span class=&quot;sr&quot;&gt;|&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\[[\w\W]&lt;/span&gt;&lt;span class=&quot;sr&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\])&lt;/span&gt;&lt;span class=&quot;sr&quot;&gt;$/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;cm&quot;&gt;/**
 * 尝试对字符串类型转换
 * @param {*} data HTML5 data-* attribute
 * @returns 
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;getData&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// 检查 data 是否是一个数字的字符串的技巧&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 如果是数字，则返回true。 如果非数字， +data 结果为 NaN。&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// 需要特别注意，+data 将空字符串 &quot;&quot; 转换为数字 0。&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;rbrace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;JSON&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;parse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;jquery-expando-设计&quot;&gt;JQuery expando 设计&lt;/h2&gt;

&lt;blockquote&gt;
  &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;JQuery.expando&lt;/code&gt; 是 jQuery 用来在 DOM 元素或其他对象上存储数据的一个独特属性。
&lt;/blockquote&gt;

&lt;h2 id=&quot;简化示例&quot;&gt;简化示例&lt;/h2&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;elem&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;document&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getElementById&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;example&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// jQuery 内部会做类似的操作&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;elem&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;jQuery123456789&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;myData&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;someValue&quot;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;};&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// 获取数据&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;elem&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;jQuery123456789&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;myData&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;];&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 输出 &quot;someValue&quot;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;设计分析&quot;&gt;设计分析&lt;/h3&gt;

&lt;h4 id=&quot;数据隔离避免冲突&quot;&gt;数据隔离/避免冲突&lt;/h4&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;JQuery.expando&lt;/code&gt; 是一个唯一的字符串（通常是由 jQuery 生成的一个带有前缀和随机数的字符串），确保它在所有元素和对象上都是唯一的。这可以避免与其他属性或数据键发生冲突。

&lt;div class=&quot;language-javascript highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// Unique for each copy of jQuery on the page&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;expando&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;jQuery&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;version&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;sr&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\D&lt;/span&gt;&lt;span class=&quot;sr&quot;&gt;/g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&quot;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;性能优化&quot;&gt;性能优化&lt;/h4&gt;

直接在元素或对象上存储数据（而不是使用全局数据存储）可以提高性能。访问和修改元素上的属性通常比通过全局数据存储更快，因为它减少了查找和管理的开销。
</description>
        <pubDate>Wed, 24 Jul 2024 07:08:37 +0000</pubDate>
        <link>https://mrrobot5.github.io/2024/07/24/note-JQuery-data-design/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2024/07/24/note-JQuery-data-design/</guid>
        
        <category>JQuery</category>
        
        
        <category>学习笔记</category>
        
      </item>
    
      <item>
        <title>Spring BeanCopier Bug</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#bug-场景&quot; id=&quot;markdown-toc-bug-场景&quot;&gt;Bug 场景&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#需要拷贝的类&quot; id=&quot;markdown-toc-需要拷贝的类&quot;&gt;①需要拷贝的类🧲&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#拷贝异常&quot; id=&quot;markdown-toc-拷贝异常&quot;&gt;②拷贝异常❌&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#日常日志&quot; id=&quot;markdown-toc-日常日志&quot;&gt;③日常日志&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#问题分析&quot; id=&quot;markdown-toc-问题分析&quot;&gt;问题分析&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#introspector&quot; id=&quot;markdown-toc-introspector&quot;&gt;①Introspector&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#beancopier&quot; id=&quot;markdown-toc-beancopier&quot;&gt;②BeanCopier&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#导出动态类&quot; id=&quot;markdown-toc-导出动态类&quot;&gt;③导出动态类&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#more&quot; id=&quot;markdown-toc-more&quot;&gt;More&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  使用Spring BeanCopier 拷贝对象过程中，发现了一个Bug。

  问题版本：3.2.0.RELEASE
&lt;/blockquote&gt;

&lt;h2 id=&quot;bug-场景&quot;&gt;Bug 场景&lt;/h2&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BeanCopier&lt;/code&gt; 是一个非常高效的复制工具，因为它在运行时生成字节码来执行复制操作，而不是使用反射。

&lt;h3 id=&quot;需要拷贝的类&quot;&gt;①需要拷贝的类🧲&lt;/h3&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TargetBean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// name&apos;s getters and setters&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// 没有 mixed 属性，Introspector 识别为布尔类型的 getter 方法&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isMixed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;contains&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;mix&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;拷贝异常&quot;&gt;②拷贝异常❌&lt;/h3&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// 创建 BeanCopier 实例。&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 作用原理：使用CGlib库生成一个新类，该类的目的是实现Java Bean 之间属性的复制。&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 在匹配和获取 TargetBean setters过程中，出现异常 java.lang.NullPointerException&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;BeanCopier&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;copier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BeanCopier&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;create&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;TargetBean&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;class&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TargetBean&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;class&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// 复制属性&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;copier&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;source&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;日常日志&quot;&gt;③日常日志&lt;/h3&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Exception in thread &quot;main&quot; java.lang.NullPointerException
        at org.springframework.cglib.core.ReflectUtils.getMethodInfo(ReflectUtils.java:424)
        at org.springframework.cglib.beans.BeanCopier$Generator.generateClass(BeanCopier.java:133)
        at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
        at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
        at org.springframework.cglib.beans.BeanCopier$Generator.create(BeanCopier.java:90)
        at org.springframework.cglib.beans.BeanCopier.create(BeanCopier.java:50)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;问题分析&quot;&gt;问题分析&lt;/h2&gt;

&lt;blockquote&gt;
  创建BeanCopier 实例的过程中，会根据TargetBean 遍历所有的 setter方法，尝试找到与之对应的 getter方法。

  如上述的场景，针对属性“mixed”, 并没有对应的 setter方法，所以报错。

  为什么 BeanCopier 会出现没有判断 null 的低级错误呢？🙉
&lt;/blockquote&gt;

&lt;h3 id=&quot;introspector&quot;&gt;①Introspector&lt;/h3&gt;

Java Bean 是一种特殊的 Java 类，&lt;strong&gt;遵循特定的命名规则&lt;/strong&gt;，比如属性的命名方式、事件处理方法等。

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Introspector&lt;/code&gt; 类使得开发者能够通过反射机制来分析一个 Java Bean 的属性和方法，而不需要直接与类的代码交互。

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// Introspector 识别的命名约定🧲&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 属性的读取方法（getter）&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;GET_PREFIX&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;get&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 属性的设置方法（setter）&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;SET_PREFIX&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;set&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// 布尔属性的特殊读取方法。对于返回类型为 boolean 的属性，按照习惯，其读取方法可以使用 &quot;is&quot; 前缀而不是 &quot;get&quot;。&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;IS_PREFIX&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;is&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

根据约定，TargetBean 中的 isMixed 方法会识别为“mixed”属性的读取方法。

&lt;h3 id=&quot;beancopier&quot;&gt;②BeanCopier&lt;/h3&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * 用CGlib库生成一个新类的过程，实现两个Java Bean之间属性的复制。
 * @see org.springframework.cglib.beans.BeanCopier.Generator#generateClass
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generateClass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ClassVisitor&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;Type&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sourceType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Type&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getType&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;source&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;Type&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targetType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Type&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getType&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

    &lt;span class=&quot;nc&quot;&gt;PropertyDescriptor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ReflectUtils&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getBeanGetters&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;source&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// Bug:  mixed 属性描述符也会返回到 setters集合中。实际上，该属性描述符并没有 WriteMethod。&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// fix: setters = ReflectUtils.getBeanSetters(this.target);&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;PropertyDescriptor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;setters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ReflectUtils&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getBeanGetters&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 遍历所有的setter方法，尝试找到与之对应的getter方法。&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;setters&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;PropertyDescriptor&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;setter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;setters&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;PropertyDescriptor&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;PropertyDescriptor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;names&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;getter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;MethodInfo&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;read&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ReflectUtils&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getMethodInfo&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;getter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getReadMethod&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// mixed 属性的描述符（setter）对应的 WriteMethod = null, 所以抛异常。&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;MethodInfo&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;write&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ReflectUtils&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getMethodInfo&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getWriteMethod&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;compatible&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;getter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;setter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;dup2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;invoke&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;read&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;invoke&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;write&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;导出动态类&quot;&gt;③导出动态类&lt;/h3&gt;

可以自定义 ClassFileTransformer， 拦截类的加载过程，并在类被加载到 JVM 之前导出类的字节码。

&lt;a href=&quot;https://github.com/MrRobot5/java-snippet&quot;&gt;使用 java agent 导出动态类&lt;/a&gt; 🧲

👉生成的动态类路径和 copy 接口实现

&lt;img src=&quot;/images/Snipaste_2024-06-05_11-09-41.png&quot; alt=&quot;BeanCopier$Generator&quot; style=&quot;zoom:50%;&quot; /&gt;

&lt;h2 id=&quot;more&quot;&gt;More&lt;/h2&gt;

其实这个是CGLIB 的bug，从 Spring 3.2 开始，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CGLIB&lt;/code&gt; 的功能被整合进了 Spring。

这个Bug 在Spring 后续版本中已经被修复。✔

不过 cglib-nodep 修复比较慢， 使用cglib-nodep 需要注意这个问题。🎈
</description>
        <pubDate>Tue, 04 Jun 2024 13:43:31 +0000</pubDate>
        <link>https://mrrobot5.github.io/2024/06/04/Spring-BeanCopier-Bug/</link>
        <guid isPermaLink="true">https://mrrobot5.github.io/2024/06/04/Spring-BeanCopier-Bug/</guid>
        
        <category>Spring</category>
        
        <category>动态代理</category>
        
        
        <category>实战问题</category>
        
      </item>
    
  </channel>
</rss>
