dromara / liteflow

Lightweight, fast, stable, and programmable component-based rule engine/process engine. Component reuse, synchronous/asynchronous orchestration, dynamic orchestration, multi-language scripting support, complex nested rules, hot deployment, smooth refreshing. Let you improve your development efficiency!
Apache License 2.0
3.04k stars 424 forks source link

建议增加Janino插件 #36

Closed zrlw closed 1 year ago

zrlw commented 1 year ago

Janino是个轻量的java编译器,超级快,所以很多重量级开源软件比如Apache Spark、Apache Flink、Presto都用它做动态代码。xx跳动把动态处理引擎从groovy迁到Janino的一个主要原因就是Janino超级快。 主要代码大致如下:

    public class JaninoScriptExecutor extends ScriptExecutor {
        // 限制:  Janino脚本Evaluator需要事先约定脚本里的变量名
        public static final String JANINO_SCRIPT_PARAMETER_NAME = "ctx";

        //  编译过的Janino脚本Evaluator缓存
        private final Map<String, IScriptEvaluator> compiledScriptMap = new CopyOnWriteHashMap<>();

        @Override
        public void load(String nodeId, String script) {
            // 创建Janino脚本Evaluator
            IScriptEvaluator se = CompilerFactoryFactory.getDefaultCompilerFactory().newScriptEvaluator();
            // 返回值类型指定为Object以支持不同脚本
            se.setReturnType(Object.class);
            // 指定Janino脚本里的变量名及类型,为通用起见,只设置一个Object类型的变量
            se.setParameters(new String[] { JANINO_SCRIPT_PARAMETER_NAME }, new Class[] { Object.class });
            // 编译
            se.cook(script);
            // 缓存编译过的Evaluator
            compiledScriptMap.put(nodeId, se);
        }

        @Override
    public Object executeScript(ScriptExecuteWrap wrap) throws Exception {
            IScriptEvaluator se = compiledScriptMap.get(wrap.getNodeId());
            // 约定首个ContextBean作为Janino脚本参数里的唯一变量,缺省是DefaultContext类型
            Object context = DataBus.getContextBeanList(wrap.getSlotIndex()).get(0);
            return se.evaluate(new Object[] { context });
        }

Janino脚本示例(变量名ctx要和上面插件代码定义的变量名一致):

import com.yomahub.liteflow.slot.DefaultContext;
((DefaultContext) ctx).setData("s1", 666); 
bryan31 commented 1 year ago

感谢,此功能将在2.11.0中实现,详情请见:https://gitee.com/dromara/liteFlow/issues/I7V6VB