0 results found
DeCo
Groovy使用
2019/05/09 java Groovy 脚本

pom依赖

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>2.4.11</version>
</dependency>

测试代码

import groovy.json.JsonSlurper;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import org.junit.Test;

/**
 * @author DC
 * @date 2019-05-09
 */
public class GroovyTest {

    private static final String JSON_STR = "{\n" +
            "    \"evalMatches\": [\n" +
            "        {\n" +
            "            \"value\": 15,\n" +
            "            \"metric\": \"Count\",\n" +
            "            \"tags\": {}\n" +
            "        }\n" +
            "    ],\n" +
            "    \"state\": \"alerting\"\n" +
            "}";


    private static final String SCRIPT = "body.evalMatches.each{message += \"指标:\" + it.metric + \",值:\" + it.value + \"\\n\" }";

    private static final String SCRIPT_RETURN = "body.evalMatches.each{message += \"指标:\" + it.metric + \",值:\" + it.value + \"\\n\" }; return message";

    @Test
    public void groovyTest() {
        // 脚本变量绑定对象
        Binding binding = new Binding();
        // groovy JSON解析器
        JsonSlurper jsonSlurper = new JsonSlurper();
        // 将json字符串转换成groovy的json对象
        Object groovyJsonObject = jsonSlurper.parseText(JSON_STR);
        // 设置groovy变量
        binding.setVariable("body", groovyJsonObject);
        binding.setVariable("message", "");
        // Groovy脚本执行器
        GroovyShell shell = new GroovyShell(binding);
        // 执行脚本()
        shell.evaluate(SCRIPT);
        // 获取变量值
        String message = String.valueOf(binding.getVariable("message"));
        System.out.println(message);
    }


    @Test
    public void groovyTest2() {
        Binding binding = new Binding();
        JsonSlurper jsonSlurper = new JsonSlurper();
        Object groovyJsonObject = jsonSlurper.parseText(JSON_STR);
        binding.setVariable("body", groovyJsonObject);
        binding.setVariable("message", "");
        // 脚本有返回值可以接受
        GroovyShell shell = new GroovyShell(binding);
        String message = (String) shell.evaluate(SCRIPT_RETURN);
        System.out.println(message);
    }

}

输出

指标:Count,值:15
请杯咖啡呗~
支付宝
微信
本文作者:DeCo
版权声明:本文首发于DeCo的博客,转载请注明出处!