实现动态切换 `schema` 的插件,并解决 PostgreSQL 的 `search_path` 缓存问题。

解读

国内互联网与金融企业普遍采用“多租户 SaaS”或“分库分表+分 schema”架构,MyBatis 作为主流 ORM,需要在一次请求内把 SQL 路由到不同 schema,且不能重启应用。PostgreSQL 的 JDBC 驱动在连接建立后会把 search_path 缓存到 PgConnection 的私有字段中,后续即使执行 SET search_path TO xxx 也不会刷新缓存,导致实际 SQL 仍走旧 schema,这是线上必现的幻读故障。面试官通过此题同时考察:

  1. MyBatis 插件(Interceptor)扩展点的深度使用;
  2. 对 PostgreSQL 协议层缓存缺陷的闭环修复;
  3. 线程安全、连接池、事务边界、性能损耗的权衡。
    答不出“缓存刷新”细节,直接降档。

知识点

  1. MyBatis 插件链路:Executor → ParameterHandler → StatementHandler → ResultSetHandler;动态切换 schema 必须在 StatementHandler 的 prepare 阶段介入,此时 SQL 已生成但尚未发送到数据库。
  2. PostgreSQL 缓存字段:org.postgresql.jdbc.PgConnection#searchPath(List<String> 私有)。
  3. 反射刷新:通过 setAccessible(true) 强制置空该字段,驱动下次会重新解析 search_path。
  4. 连接池影响: Druid、HikariCP 均会缓存连接,必须绑定到当前 Connection 维度,而非线程变量。
  5. 事务边界:若使用 Spring 声明式事务,切换动作必须在事务开启前完成,否则同一连接内的后续 SQL 仍复用旧缓存。
  6. 性能优化:对同一连接同一 schema 的重复切换,用 LRU 本地缓存记录已刷新过的 schema → connectionId,避免每秒上百次反射。
  7. 安全兜底:插件需捕获 SET search_path 执行异常,降级为 创建新连接(设置 druid.validConnectionChecker 或 hikari.connectionTestQuery),防止缓存刷新失败导致脏读。

答案

1. 插件入口

@Intercepts({
  @Signature(type = StatementHandler.class, method = "prepare",
             args = {Connection.class, Integer.class})
})
public class SchemaSwitchInterceptor implements Interceptor {
    private final LRUCache<String, Boolean> refreshedCache = new LRUCache<>(1024);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler handler = (StatementHandler) invocation.getTarget();
        MappedStatement ms = (MappedStatement) 
            MetaObject.forObject(handler).getValue("delegate.mappedStatement");
        String schema = determineSchema(ms);          // 从 ThreadLocal/注解/租户上下文获取
        if (StringUtils.isBlank(schema)) {
            return invocation.proceed();
        }
        Connection conn = (Connection) invocation.getArgs()[0];
        String cacheKey = conn.toString() + ":" + schema;
        if (refreshedCache.get(cacheKey) == null) {
            switchSchema(conn, schema);
            refreshedCache.put(cacheKey, true);
        }
        return invocation.proceed();
    }

    private void switchSchema(Connection conn, String schema) throws SQLException {
        String sql = "SET search_path TO " + schema + ",public";
        try (Statement stmt = conn.createStatement()) {
            stmt.execute(sql);
        }
        // 关键:刷新 PostgreSQL 缓存
        if (conn.isWrapperFor(PgConnection.class)) {
            PgConnection pgConn = conn.unwrap(PgConnection.class);
            Field field = PgConnection.class.getDeclaredField("searchPath");
            field.setAccessible(true);
            field.set(pgConn, null);   // 强制清空,驱动下次重新解析
        }
    }
}

2. 与 Spring 集成

@Configuration
public class MyBatisConfig {
    @Bean
    public SchemaSwitchInterceptor schemaSwitchInterceptor() {
        return new SchemaSwitchInterceptor();
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource ds, 
               SchemaSwitchInterceptor interceptor) throws Exception {
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(ds);
        fb.setPlugins(new Interceptor[]{interceptor});
        return fb.getObject();
    }
}

3. 事务前置校验
在 Spring 的 @Transactional 切面之前,通过 TransactionSynchronizationManager 注册回调,确保 schema 切换在 ConnectionHolder 创建前完成,避免“连接已缓存但 schema 未刷新”的竞态。

4. 灰度与监控

  • 增加 Micrometer 指标:记录每秒反射次数、缓存命中率;
  • 若命中率低于 80%,提示“连接池 size 过大或 schema 热点过于分散”,及时调优。

拓展思考

  1. 跨库场景:若租户粒度是 database 而非 schema,需切换到 ShardingSphere 的 ShadowDataSource 或 Spring AbstractRoutingDataSource,此时插件应升级为 多数据源动态路由,而非单连接内切换。
  2. 只读副本:PostgreSQL 读写分离通常用 replica pgpool,插件需在 switchSchema 后追加 SET default_transaction_read_only = on,防止误写。
  3. 连接池预热:启动阶段执行 SELECT 1 FROM information_schema.tables 并触发一次 search_path 刷新,可把首次请求耗时从 30 ms 降到 5 ms。
  4. 无反射方案:PostgreSQL 42.3.0 之后提供 PGProperty.REWRITE_SEARCH_PATH,可在 JDBC URL 追加 ?rewriteSearchPath=true,但国内生产环境普遍停留在 42.2.x,反射仍是唯一可靠方案。
  5. 面试加分项:提及“把 schema 切换下沉到 sidecar(如 istio+envoy)”,实现语言无关的多租户隔离,展示对云原生的深度思考。