In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
这篇文章主要为大家展示了"Java动态脚本Groovy的特性是什么",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"Java动态脚本Groovy的特性是什么"这篇文章吧。
1.Groovy特性
可将java代码在Groovy脚本动态编码、代码被修改达到不重启服务的目的(类似于热部署)
2.核心涉及
ClassLoader:就是类的装载器,它使JVM可以动态的载入Java类,JVM并不需要知道从什么地方(本地文件、网络等)载入Java类,这些都由ClassLoader完成。
GroovyClassLoader:动态地加载一个脚本并执行它的行为。GroovyClassLoader是一个定制的类装载器,负责解释加载Java类中用到的Groovy类。
3.Java与Groovy转换
第一步:引入Groovy依赖
org.codehaus.groovy groovy 2.5.14 第二步:创建interface接口声明方法
public interface CallAnalysis { default void load() { }}第三步:在resources目录下创建.groovy文件
package groovyimport com.example.groovy.testgroovy.task.CallAnalysisimport groovy.util.logging.Slf4j@Slf4jclass CallAnalysisImpl implements CallAnalysis{ @Override void load() { log.info("我被Groovy脚本加载...") }}第四步:创建Groovy脚本装载类,动态解析脚本为Class
package com.example.groovy.testgroovy.task;import groovy.lang.GroovyClassLoader;public class GroovyUtils { private final static ClassLoader classLoader = GroovyUtils.class.getClassLoader();//获取当前类装载器 //ClassLoader:就是类的装载器,它使JVM可以动态的载入Java类,JVM并不需要知道从什么地方(本地文件、网络等)载入Java类,这些都由ClassLoader完成。 public final static GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader); //GroovyClassLoader:负责在运行时编译groovy源代码为Class的工作,从而使Groovy实现了将groovy源代码动态加载为Class的功能。 /** * . * 获取实例化对象 * @param script groovy脚本内容 * @param * @return * @throws IllegalAccessException * @throws InstantiationException */ public static T instanceTaskGroovyScript(String script) throws IllegalAccessException, InstantiationException { Class taskClz = groovyClassLoader.parseClass(script); T instance = (T) taskClz.newInstance(); return instance; }}第五步:读取脚本内容,执行脚本
package com.example.groovy.testgroovy.task;import lombok.extern.slf4j.Slf4j;import org.apache.commons.io.FileUtils;import org.springframework.stereotype.Component;import java.io.File;import java.io.IOException;@Slf4j@Componentpublic class CallAnalysisGroovyTask { /** * . * 读取脚本内容 * * @return */ public static String getGroovy() { String context = ""; try { String path = "E:\\IDEAFile\\testgroovy\\src\\main\\resources\\groovy\\CallAnalysisImpl.groovy"; context = FileUtils.readFileToString(new File(path));//将脚本内容转为字符串 } catch (IOException e) { log.error("file is not found[{}]", e); } return context; } /** * . * 执行groovy脚本 * * @param script */ public static void execGroovy(String script) { try { CallAnalysis objClass = GroovyUtils.instanceTaskGroovyScript(script);//获取实例对象 objClass.load();//调用脚本方法 } catch (Exception t) { log.error("execGroovy file {} error", script); } } /** * . * main方法 * @param args */ public static void main(String[] args) { System.out.println("=================="); CallAnalysisGroovyTask task = new CallAnalysisGroovyTask(); String script = task.getGroovy();//获取脚本 execGroovy(script);//实例化脚本,执行方法 System.out.println("=================="); }}
4. Groovy Feature Verification
Use Groovy scripting features to modify data in real time without restarting services
Step 1: Modify the previous Groovy script data. Store in database table, load script dynamically
@Slf4jclass CallAnalysisImpl implements CallAnalysis { private int anInt = 10; private int bnInt = 10; @Override void load() { log.info ("Current Class:[{}]", this.getClass().getName()) log.info ("I was loaded by Groovy script... ") log.info ("Calculation result:[{}]", (anInt + bnInt)) }} Step 2: Add and query Groovy scripts to database tables, dynamically load and execute
/** * . * Read scripts and perform warehousing operations * * @return */ @GetMapping("/saveScript") public String saveScript() { String scriptStr = callAnalysisGroovyTask.getGroovy(); Script = newScript();//Entity class object script.setScript(scriptStr);//Script content script.setRuleId("1");//rule id script.setScriptName("Demo 1");//script name service.save(script); return "Added successfully"; } /** * . * Get scripts dynamically from database tables * * @param ruleId rule id * @return Script content */ @GetMapping("/groovy") public String groovy(final String ruleId) { Script scr = scriptService.findScriptByRuleId(ruleId);//query by rule id String scriptStr = scr.getScript(); callAnalysisGroovyTask.execGroovy(scriptStr); return scriptStr; }
Add results:
Query results, console execution results:
Step 3: Modify the table data value several times and view the execution result.
That's all for Java Dynamic Script Groovy, thanks for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.