集成 `mybatis-sql-audit` 插件,拦截全表扫描并抛出异常。

解读

国内互联网面试中,**“如何防止线上全表扫描”**是 MyBatis 高频安全考点。面试官不关心你是否真的用过 mybatis-sql-audit,而是考察:

  1. 对 MyBatis 插件链(Interceptor 链) 的掌握深度;
  2. 能否 在不改业务代码的前提下,通过插件机制 识别并阻断危险 SQL;
  3. 对 SQL 解析、执行计划、索引规则 的综合理解;
  4. 线上灰度、降级、告警等 稳定性设计思维。

一句话:让你现场写一个“轻量级、可热插拔、可灰度”的全表扫描防火墙。

知识点

  1. MyBatis 插件四大对象:Executor、ParameterHandler、ResultSetHandler、StatementHandler;全表扫描拦截必须绑定到 Executor.query 方法。
  2. BoundSql 对象保存最终待提交 SQL,MetaObject 可安全读写私有字段。
  3. SQL 解析引擎:国内项目普遍用 Druid WallVisitor 或 JSqlParser,可提取表名、WHERE 条件、索引字段。
  4. 执行计划获取:MySQL 用 EXPLAIN,Oracle 用 EXPLAIN PLAN FOR,必须复用原 Connection 避免事务漂移。
  5. 规则引擎:扫描行数 type = ALL 且 rows > 阈值(默认 5000) 即判定全表扫描;阈值可动态配置。
  6. 异常策略:抛出自定义 FullTableScanException,错误码 9001,附带 SQL、参数、建议索引,方便监控大盘聚合。
  7. 灰度开关:基于 Apollo / Nacos 配置 sql.audit.enable 和 sql.audit.gray.users,支持按用户维度白名单。
  8. 性能保护:采用 本地 LRU 缓存 缓存 SQL 指纹的 EXPLAIN 结果,缓存时间 30 s,避免高频解析拖垮数据库。
  9. Spring 集成:插件类加 @Component 并配置 @Intercepts签名,order 值必须小于 0,保证在分页插件之前执行。
  10. 上线流程:灰度 → 告警 → 阻断,先告警 3 天,再抛异常,给业务方留改造窗口。

答案

@Component
@Intercepts({
    @Signature(type = Executor.class, method = "query",
               args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class FullTableScanInterceptor implements Interceptor {

    private static final Logger log = LoggerFactory.getLogger(FullTableScanInterceptor.class);

    @Autowired
    private ConfigService configService;   // Apollo/Nacos

    private final Cache<String, ExplainResult> cache = Caffeine.newBuilder()
            .maximumSize(10_000).expireAfterWrite(30, TimeUnit.SECONDS).build();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 1. 全局开关
        if (!configService.getBooleanProperty("sql.audit.enable", false)) {
            return invocation.proceed();
        }

        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        BoundSql boundSql = ms.getBoundSql(parameter);
        String sql = boundSql.getSql().toLowerCase().replaceAll("\\s+", " ").trim();

        // 2. 只拦截 SELECT
        if (!sql.startsWith("select")) {
            return invocation.proceed();
        }

        // 3. 白名单用户
        String user = SqlContextHolder.getUser(); // 自定义ThreadLocal
        if (configService.getProperty("sql.audit.gray.users", "").contains(user)) {
            return invocation.proceed();
        }

        // 4. 缓存指纹
        String key = sql + "|" + ms.getId();
        ExplainResult explain = cache.get(key, k -> doExplain(ms, boundSql));
        if (explain == null) {
            return invocation.proceed(); // EXPLAIN 失败,保守放行
        }

        // 5. 规则判断
        if ("ALL".equals(explain.type) && explain.rows > configService.getIntProperty("sql.audit.rows.threshold", 5000)) {
            String msg = String.format("全表扫描拦截:SQL=[%s], 扫描行数=%d, 建议索引=%s",
                                       sql, explain.rows, explain.extra);
            log.error(msg);
            throw new FullTableScanException("9001", msg);
        }
        return invocation.proceed();
    }

    private ExplainResult doExplain(MappedStatement ms, BoundSql boundSql) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = ms.getConfiguration().getEnvironment().getDataSource().getConnection();
            String explainSql = "EXPLAIN " + boundSql.getSql();
            stmt = conn.prepareStatement(explainSql);
            // 参数绑定
            ParameterHandler handler = new DefaultParameterHandler(ms, boundSql.getParameterObject(), boundSql);
            handler.setParameters(stmt);
            rs = stmt.executeQuery();
            if (rs.next()) {
                ExplainResult r = new ExplainResult();
                r.type = rs.getString("type");
                r.rows = rs.getLong("rows");
                r.extra = rs.getString("Extra");
                return r;
            }
        } catch (Exception e) {
            log.warn("EXPLAIN 失败", e);
        } finally {
            if (rs != null) try { rs.close(); } catch (SQLException ignore) {}
            if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
            if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
        }
        return null;
    }

    private static class ExplainResult {
        String type;
        long rows;
        String extra;
    }

    @Override
    public void setProperties(Properties properties) {}
}

使用步骤:

  1. 引入 mybatis-sql-audit 包(或直接把上面类放到项目);
  2. Apollo 新增配置:
    sql.audit.enable = true
    sql.audit.rows.threshold = 5000
    sql.audit.gray.users = user1,user2
    
  3. 启动观察日志,出现 9001 错误码即表示拦截成功;
  4. 上线顺序:先告警 3 天,再开启抛异常,避免一刀切导致 P0 故障。

拓展思考

  1. 分库分表怎么办?
    插件同样生效,但 EXPLAIN 只能针对物理表,需把 逻辑表名还原成带分片的真实表名;可继承 ShardingSphere 的 SQLRouteHook 做联动。

  2. MySQL 8.0 以后 EXPLAIN 格式变化?
    增加 EXPLAIN FORMAT=JSON,可精确拿到 cost 值,用 cost > 100000 作为拦截条件更科学。

  3. 写入场景如何防全表更新?
    拦截 Executor.update,识别 UPDATE/DELETE 缺少 WHERE 或影响行数 = 全表,规则与查询类似,但需 在事务提交前做二次确认,避免误杀。

  4. 多数据源如何只拦截指定库?
    在插件里通过 ms.getConfiguration().getEnvironment().getId() 拿到 数据源名称,配置 sql.audit.db.list=trade,order,非名单库直接放行。

  5. 与 Druid WallFilter 冲突?
    Druid 侧重 SQL 注入防御,本插件侧重 性能与扫描行数,两者 order 值错开(WallFilter=1,本插件=0)即可共存。

  6. 上线后业务报错如何快速止血?
    Apollo 一键关闭开关 → 配置 sql.audit.enable=false → 30 秒内全部客户端生效,无需重启,满足国内 “变更 5 分钟可回滚” 的稳定性规范。