zoukankan      html  css  js  c++  java
  • Groovy语言学习--语法基础(4)

    语法基础到此就结束了,毕竟其和Java许多地方并无差别。groovy作为脚本,是为了能更好地随业务变化调整规则,我根据自己对规则的理解

    通过一张图简单描述一个groovy脚本场景:由于货币膨胀,经济收缩等未来一年的报价策略是变动的而且是未知的,可能到2019年的时候我们需要重新

    写一个报价策略在代码中维护,为了不变更项目代码和服务停机等故障,通常我们会写一个规则引擎,当然我们也可以通过groovy脚本来织入新的策略,

    有点像spring aop,所以groovy就是一把利器。

     语法基础Demo,简述java织入groovy脚本的四种方式。

    新建maven项目,项目结构如下: 

    引入对应的maven依赖:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>slow</groupId>
        <artifactId>city</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    
        <name>city</name>
        <!-- FIXME change it to the project's website -->
        <url>http://www.example.com</url>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.2.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
    
    
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-validation</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.session</groupId>
                <artifactId>spring-session-core</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.codehaus.groovy</groupId>
                <artifactId>groovy-all</artifactId>
                <version>2.4.10</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <pluginManagement><!-- lock down plugins versions to avoid using Maven 
                    defaults (may be moved to parent pom) -->
                <plugins>
                    <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                    <plugin>
                        <artifactId>maven-clean-plugin</artifactId>
                        <version>3.1.0</version>
                    </plugin>
                    <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <version>3.0.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.8.0</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>2.22.1</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>3.0.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-install-plugin</artifactId>
                        <version>2.5.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                    </plugin>
                    <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                    <plugin>
                        <artifactId>maven-site-plugin</artifactId>
                        <version>3.7.1</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-project-info-reports-plugin</artifactId>
                        <version>3.0.0</version>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>
    </project>

    在Java中集成Groovy应用的四种方式:GroovyShell   GroovyScriptEngine  GroovyClassLoader  JavaApi

     
    import groovy.lang.Binding;
    import groovy.lang.GroovyClassLoader;
    import groovy.lang.GroovyObject;
    import groovy.lang.GroovyShell;
    import groovy.util.GroovyScriptEngine;
    
    import java.io.File;
    
    import javax.script.Invocable;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    
    import org.jboss.logging.Logger;
    
    public class GroovyJavaExample {
    
        Logger log = Logger.getLogger(getClass());
        /*
         * GroovyShell
         */
        public String groovySheel() {
            Binding binding = new Binding();
            binding.setVariable("name", "Tom");
            binding.setVariable("age", 16);
            binding.setProperty("favourite", "play paino");
            GroovyShell shell = new GroovyShell(binding);
            String script = "println "welcome to $name ;age is $age;favourite is $favourite "; return favourite";
            Object value = shell.evaluate(script);
            log.info("value:" + value);
            return value.toString();
        }
    
        /*
         * GroovyScriptEngine
         */
        public String groovyScriptEngineExample() {
            String result = "";
            try {
                // 定义groovy脚本引擎的根路径
                String[] roots = new String[] { ".\src\main\groovyscript" };  
                GroovyScriptEngine engine = new GroovyScriptEngine(roots);
    
                Binding binding = new Binding();
                binding.setVariable("language", "groovy");
                // script.groovy 脚本引擎根路径下的 脚本名
                Object value = engine.run("script.groovy", binding);
                log.info("value:" + value);
                result = value.toString();
            } catch (Exception e) {
                log.error(e);
            }
            return result;
        }
    
        @SuppressWarnings({ "rawtypes" })
        public String groovyClassLoader() {
            GroovyClassLoader loader = null;
            try {
                loader = new GroovyClassLoader();
                String groovyFilePath = "E:/workspace-eclipse/city/src/main/groovyscript/groovy1.groovy";
                Class groovyClass = loader.parseClass(new File(groovyFilePath));
                GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
                String result = (String) groovyObject.invokeMethod("fun", "你好");
    
                log.info("groovy 脚本返回的结果:" + result);
    
                loader.close();
            } catch (Exception e) {
                log.error(e);
            } 
            return null;
        }
    
        /*
         * java specification request 223 ScriptEngine接口
         */
        public String jsrApi() {
            String result = "";
            ScriptEngineManager factory = new ScriptEngineManager();
            ScriptEngine engine = factory.getEngineByName("groovy");
            String helloLanguage = "def hello(language){return "hello $language"}";
            try {
                engine.eval(helloLanguage);
    
                Invocable inv = (Invocable) engine;
                Object[] params = {"Groovy"};
                Object value = inv.invokeFunction("hello", params);
                log.info("value: " + value);
                result = value.toString();
            } catch (Exception e) {
                log.error(e);
            }
            return result;
        }
    }

    相关的groovy脚本

    groovy1.groovy

     println "hello groovy script"
     
     def String fun(String args){
    	 
    	 println args
    	 return "hello lover"
     }
    

    loaderScript.groovy

    package slow.city
    
    class LoaderScript {
    
    	public createFile(String fileName){
    		File file = new File(fileName);
    		file.createNewFile();
    	}
    }
    

      

    script.groovy

    package slow.city
    
     println "welcome to ${}"
     return "are you ok"
    

      

    代码比较简单,必要的地方已经附加了相应的解释。在实际的项目生产中,把groovy代码直接存储到数据库中,通过对数据库groovy脚本内容的更改,

    进而变更相对应的规则。大概图示如下。后续想着如何对groovy进行封装,使之能在项目中简单调用。

      

  • 相关阅读:
    设置debian的静态IP
    《深入理解Java虚拟机》学习笔记之最后总结
    《深入理解Java虚拟机》学习笔记之字节码执行引擎
    《深入理解Java虚拟机》学习笔记之类加载
    《深入理解Java虚拟机》学习笔记之工具
    《深入理解Java虚拟机》学习笔记之内存回收
    Proxy源码解析
    Mysql索引
    搞定Hotspot-api
    JNI链接
  • 原文地址:https://www.cnblogs.com/slowcity/p/10173564.html
Copyright © 2011-2022 走看看