Groovy&Java动态编译执行
工作中,遇到部分业务经常动态变化,或者在不发布系统的前提下,对业务规则进行调整。那么可以将这部分业务逻辑改写成Groovy脚本来执行,那么就可以在业务运行过程中动态更改业务规则,达到快速响应。
Case1: Groovy动态编译执行
闲话少说,直接上代码:
static Compilable engine; //获取groovy编译类
static {
ScriptEngineManager manager = new ScriptEngineManager();
engine = (Compilable) manager.getEngineByName("groovy");
}
public static Object execute(String scriptText, Map, ?> context) {
CompiledScript script = engine.compile(scriptText); // 这个地方需要使用缓存,达到编译一次,多次执行。
if (script != null) {
ScriptContext scriptContext = new SimpleScriptContext();
Set> its = context.entrySet(); //上下文参数
for(Object o:its){
@SuppressWarnings("rawtypes")
Entry entry = (Entry)o;
scriptCont