导购场景下的Groovy脚本引擎实战( 四 )


private void executeScriptBinary(ScriptExecuteContext context, GroovyStandardScriptExecuteContext GroovyContext) {Runnable scriptRunTask = instanceScriptRunTask(context, GroovyContext);scriptRunTask.run();}private Runnable instanceScriptRunTask(ScriptExecuteContext context, GroovyStandardScriptExecuteContext GroovyContext) {return () -> {try {//获取转化后的Groovy文件Class scriptClass = GroovyContext.getScriptClass();//获取脚本作用域的参数和变量Binding scriptBinding = GroovyContext.getScriptBinding();//获取Groovy的构建类Constructor constructor = scriptClass.getConstructor(Binding.class);//初始化Groovy类实例Object scriptClassInstance = constructor.newInstance(scriptBinding);//获取Groovy中的run方法Method run = scriptClass.getDeclaredMethod("run");//执行GroovyObject result = run.invoke(scriptClassInstance);//设置返回结果ScriptExecuteResult scriptExecuteResult = new ScriptExecuteResult(result);context.setScriptExecuteResult(scriptExecuteResult);} catch (Exception e) {if (e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() instanceof IllegalArgumentException) {throw new BaseException(((InvocationTargetException) e).getTargetException().getMessage());} else {log.error(LogUtil.exceptionMessage("scriptRunTaskException", e));throw new BaseException("脚本执行时发生异常");}} finally {log.info(LogUtil.message("GroovyStandardScriptSandBoxContext", GroovyContext.getGroovyStandardScriptSandBoxContext()));}};}
5.1.3封装返回结果
Object result = Optional.ofNullable(scriptExecuteContext.getScriptExecuteResult()).map(ScriptExecuteResult::getResult).orElse(null);SlsEntity slsEntity = SlsEntity.builder().put("scriptCode", request.getScriptCode()).put("businessStatus", "SUCCESS").put("requestTime", DateUtil.formatDateTime(requestTime)).put("consumingTime", String.valueOf(stopWatch.getTime(TimeUnit.MILLISECONDS)));SLog.info(slsEntity,"{} | {} ",request.getScriptCode(), "SUCCESS"
6.总结