使用 GroovyScriptEngine 池化复用

解读

在国内一线互联网或金融企业的高并发服务中,Groovy 常被用作规则引擎、动态配置、营销活动脚本等场景。每一次 new GroovyScriptEngine() 都会重新初始化编译器、类加载器与元数据,频繁创建会造成 Metaspace 暴涨、GC 停顿拉长,直接触发线上告警。因此面试官真正想考察的是:

  1. 你是否清楚 GroovyScriptEngine 的生命周期成本;
  2. 能否给出线程安全、可扩展、可监控的池化方案;
  3. 是否了解脚本缓存、ClassLoader 泄漏、热更新等落地细节。

一句话:不是“能不能跑”,而是“敢不敢上生产”。

知识点

  1. GroovyScriptEngine 内部持有GroovyClassLoader,每次 parseClass 会生成新类并加载到 Metaspace,默认无过期回收。
  2. GroovyClassLoader 不是线程安全对象,多线程共用需加锁或使用 ThreadLocal 副本。
  3. 池化目标:复用编译结果,而不是复用引擎实例;脚本缓存 key = 脚本内容 MD5 + 脚本版本号。
  4. 生产级必须配套脚本白名单、编译超时、沙箱拦截(SecuredAST)、资源统计(编译耗时、加载类数)。
  5. 国内大厂常用双缓存策略:一级 Guava Cache 存 CompiledScript,二级 Caffeine 存 Class 字节码,配合 LRU + 权重回收,防止内存爆炸。

答案

给出一份可直接落地的轻量级池化实现,兼顾线程安全、热更新、内存防护:

@Singleton
class GroovyEnginePool {
    // 脚本内容 → CompiledScript 缓存,30 分钟无访问自动淘汰
    private final Cache<String, CompiledScript> scriptCache = Caffeine.newBuilder()
            .maximumWeight(50_000_000)          // 约 5000 个脚本
            .weigher { k, v -> k.size() + 256 } // 粗略权重
            .expireAfterAccess(30, TimeUnit.MINUTES)
            .removalListener { k, v, r -> 
                if (r == RemovalPolicy.REPLACED) return
                // 记录卸载,防止 ClassLoader 泄漏
                GroovySystem.getMetaClassRegistry().removeMetaClass(v.scriptClass)
            }
            .recordStats()
            .build()

    // 引擎实例本身很轻量,但 ClassLoader 很重,所以只用一个,并加读写锁
    private final GroovyScriptEngine engine = new GroovyScriptEngine([])
    private final ReadWriteLock lock = new ReentrantReadWriteLock()

    Object eval(String scriptText, Map<String, Object> context) {
        String key = DigestUtils.md5Hex(scriptText)
        CompiledScript compiled = scriptCache.get(key) {
            lock.writeLock().with {
                // 双重检查,防止重复编译
                scriptCache.getIfPresent(key) ?: doCompile(scriptText, key)
            }
        }
        Bindings binding = new SimpleBindings(context)
        compiled.eval(binding)
    }

    private CompiledScript doCompile(String text, String key) {
        // 编译沙箱:限制导入、限制方法
        def config = new CompilerConfiguration()
        config.addCompilationCustomizers(new SecureASTCustomizer(
                importsWhitelist: ['java.lang.*', 'java.util.*'],
                staticImportsWhitelist: [],
                tokensWhitelist: SecureASTCustomizer.DEFAULT_TOKENS_WHITELIST,
                constantTypesClassesWhiteList: [Integer, Long, String, Boolean]
        ))
        def loader = new GroovyClassLoader(this.class.classLoader, config)
        // 引擎内部会缓存 Class,但我们要自己管生命周期
        def clazz = loader.parseClass(text, "Script_" + key)
        new CompiledScript(clazz, loader)
    }

    // 监控数据,对接 Prometheus
    Map<String, Object> stats() {
        def stats = scriptCache.stats()
        [
            hitRate      : stats.hitRate(),
            evictionCount: stats.evictionCount(),
            loadedCount  : scriptCache.estimatedSize()
        ]
    }
}

// CompiledScript 包装,持有 Script 实例与对应 ClassLoader
class CompiledScript {
    final Class<Script> scriptClass
    final GroovyClassLoader loader
    CompiledScript(Class<Script> clazz, GroovyClassLoader loader) {
        this.scriptClass = clazz
        this.loader = loader
    }
    Object eval(Bindings binding) {
        Script script = scriptClass.newInstance()
        script.binding = binding
        script.run()
    }
}

使用示例:

def pool = GroovyEnginePool.instance
def result = pool.eval('return a + b', [a: 1, b: 2])
assert result == 3

关键点强调:

  • 缓存 key 用内容摘要,保证同名脚本变更后可热更新;
  • 读写锁只阻塞首次编译,后续无锁快速返回;
  • 通过 Caffeine 的权重回收与RemovalListener主动清理 MetaClass,杜绝 ClassLoader 泄漏;
  • 统计指标直接映射到Prometheus + Grafana,方便 SRE 统一监控。

拓展思考

  1. 如果脚本量超过 10 万(如金融风控规则),上述单节点内存方案会失效,可引入远程编译服务:
    • 编译集群把脚本编译成字节流,通过gRPC 返回 SHA256 + 字节数组;
    • 业务进程只缓存字节数组 + GroovyClassLoader.defineClass,本地不存源码,大幅降低内存。
  2. 对于毫秒级延迟要求(广告投放引擎),可预编译成字节码文件,启动时批量加载,完全跳过 parse 阶段,QPS 提升 3 倍以上。
  3. 国内合规要求脚本留痕审计,需在编译阶段把源码、操作人、时间戳写入数据库版本表,并与缓存 key 绑定,实现一键回滚。
  4. 如果跑在云原生环境,可把脚本缓存放到Redis + Sidecar 模式,Pod 重启后秒级预热,避免冷启动带来的超时熔断。