基于 Groovy 脚本实现读写分离
解读
国内互联网面试中,“读写分离”不仅考察候选人是否理解主从架构,更关注**“如何在脚本层无侵入地切换数据源”。Groovy 常用于 Gradle 插件、SpringCloud 的胶水代码或 Spock 测试,面试官期望你利用闭包、动态代理、运行时元编程等 Groovy 独有特性,在不改动业务代码**的前提下完成路由。回答时要突出“脚本化”“零配置”“可热替换”三个关键词,并给出可落地的 Groovy ClassLoader 隔离方案,避免空谈 Spring 的 AbstractRoutingDataSource。
知识点
- Groovy 闭包委托策略(Delegate First)——实现 DSL 级数据源切换
- GroovyObject.invokeMethod 与 ExpandoMetaClass——运行时替换 getConnection()
- @Category / @Mixin——为 java.sql.DataSource 动态追加“readOnly”标志
- GroovyClassLoader.parseClass——脚本热加载,保证灰度发布无需重启
- Spock 数据驱动测试——使用 where 块验证主从延迟容忍度
- Gradle 插件写法——在 buildSrc 中封装读写分离逻辑,供多微服务复用
答案
以下脚本可直接放在 src/main/groovy/script 目录,通过 groovy -cp . ReadWriteSplit.groovy 运行,无需 Spring 容器即可实现读写分离。
@Grab('com.zaxxer:HikariCP:5.0.1')
@Grab('mysql:mysql-connector-java:8.0.33')
import com.zaxxer.hikari.HikariDataSource
import groovy.sql.Sql
// 1. 配置两个数据源
def createHikari(url, user, pwd, readOnly) {
def ds = new HikariDataSource(
jdbcUrl: url, username: user, password: pwd,
maximumPoolSize: readOnly ? 10 : 5,
connectionTimeout: 2000
)
// 利用 Groovy 动态为 DataSource 打标签
ds.metaClass.isReadOnly = { -> readOnly }
return ds
}
def writeDs = createHikari('jdbc:mysql://10.0.0.1:3306/order', 'w_user', 'w_pwd', false)
def readDs = createHikari('jdbc:mysql://10.0.0.2:3306/order', 'r_user', 'r_pwd', true)
// 2. 路由闭包,采用 Delegate First 策略
def withSql = { boolean isRead, Closure c ->
def target = isRead ? readDs : writeDs
def sql = new Sql(target)
try {
c.delegate = sql
c.resolveStrategy = Closure.DELEGATE_FIRST
c.call()
} finally {
sql.close()
}
}
// 3. 业务代码零侵入
withSql(true) { // 读从库
def list = rows('SELECT * FROM t_order WHERE user_id=?', [1001])
println "read ${list.size()} rows"
}
withSql(false) { // 写主库
executeInsert('INSERT INTO t_order(user_id,amount) VALUES(?,?)', [1001, 99])
}
// 4. 灰度热加载支持
if (new File('route.groovy').exists()) {
def clazz = new GroovyClassLoader().parseClass(new File('route.groovy'))
def route = clazz.newInstance(writeDs, readDs)
route.withSql(true) { println rows('SELECT 1') }
}
关键点
- 用闭包委托把 Sql 实例注入业务块,消灭样板代码
- 为 DataSource 动态追加
isReadOnly属性,后续可对接 Druid 的wall过滤器做只读 SQL 校验 - 通过
GroovyClassLoader.parseClass实现脚本级灰度,满足国内“不停服发布”要求
拓展思考
- 事务一致性:Groovy 脚本环境没有 Spring 的
@Transactional,可借助groovy.sql.Sql.withTransaction并在闭包内二次路由到主库,避免只读库开启事务导致失败。 - 延迟敏感业务:在闭包入口处增加
SlaveLagVerifier——通过SHOW SLAVE STATUS解析Seconds_Behind_Master,若延迟 >1s 自动降级到主库,把降级逻辑写在 Groovy 脚本里,方便测试与回滚。 - Gradle 插件化:把
withSql闭包封装为readWriteSplit{}DSL,发布到私有仓库,一行apply plugin: 'rw-split'即可让所有微服务脚本具备读写分离能力,符合国内“中台”快速复用思路。 - 安全审计:利用 Groovy 的
AstTransformation在编译期扫描 SQL,禁止读库出现写语句,一旦违规直接抛SecurityException,在 CI 阶段即可拦截。