tio-boot 整合 Groovy

什么是 Groovy

Groovy 是一种运行在 Java 平台上的动态语言,它完全与 Java 兼容,同时也提供了一些更现代化的编程特性。Groovy 是为了提高开发人员的生产力而设计的,它的语法对于 Java 开发者来说很容易上手,因为 Groovy 可以无缝地与 Java 代码和库集成。

Groovy 的主要特点包括:

  1. 简化的语法:Groovy 的语法比 Java 更简洁,去掉了一些冗余的关键字和标点,例如分号可以省略,方法定义不需要指定返回类型(如果不想指定的话)。
  2. 动态特性:Groovy 是一种动态语言,它支持运行时元编程、动态类型、闭包等特性。这使得 Groovy 非常适合编写脚本或快速开发应用。
  3. 强大的集合处理能力:Groovy 提供了扩展的集合 API 和一系列内建的集合处理方法,如each, collect, find, groupBy等,这些方法大大简化了对集合的操作。
  4. 内建语言特性:Groovy 内置了对 XML 和 JSON 的直接支持,使得处理这些数据格式非常便捷。
  5. 闭包支持:Groovy 的闭包是对 Java 匿名内部类的一种强大的替代方式,它支持简短语法和直接访问闭包外部的变量。
  6. 编译和脚本双模式:Groovy 代码可以被编译成 Java 字节码,也可以作为脚本直接运行,这为开发提供了极大的灵活性。
  7. 与 Java 的无缝集成:Groovy 可以直接使用所有的 Java 类库,Java 代码也可以直接调用 Groovy 类和方法,这使得 Groovy 在现有的 Java 项目中非常容易被集成。

应用场景

  1. 快速开发:Groovy 的动态特性和简化的语法使其成为快速开发原型和小型应用的理想选择。
  2. 测试脚本:Groovy 常被用于编写自动化测试脚本,特别是在使用 Spock(一个基于 Groovy 的测试框架)时。
  3. 构建脚本:Groovy 是 Gradle 构建工具的基础语言,这使得 Groovy 成为编写构建和部署脚本的流行选择。
  4. Web 应用开发:Groovy 可以用于 Web 应用开发,尤其是与 Grails 框架结合使用时。Grails 是一个基于 Groovy 的全栈 Web 应用框架,提供了类似于 Ruby on Rails 的开发体验。

Groovy 的这些特性使它成为 Java 生态系统中一个非常有价值和灵活的补充,能够在许多不同的开发场景中提供帮助。

tio-boot 整合 Groovy 脚本

在 tio-boot 中调用 Groovy 脚本处理 web 请求

要在 tio-boot 中调用并运行 Groovy 脚本,你首先需要添加 Groovy 语言的支持,然后编写相应的 Java 代码来执行 Groovy 脚本。下面是详细的步骤和示例:

1. 添加 Groovy 依赖

在你的项目中,需要添加 Groovy 的依赖来支持 Groovy 脚本的执行。在你的 pom.xml 文件中添加以下依赖:

<dependency>
  <groupId>org.codehaus.groovy</groupId>
  <artifactId>groovy</artifactId>
  <version>3.0.9</version> <!-- 请根据实际情况选择适合的版本 -->
</dependency>

2. 编写 Groovy 脚本处理器

创建一个用于执行 Groovy 脚本的处理器。这里我们模仿你之前提供的 Magic Script 的用法来整合 Groovy 脚本。

package com.litongjava.grovvy;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

import com.litongjava.jfinal.aop.Aop;
import com.litongjava.tio.utils.hutool.ResourceUtil;

import groovy.lang.GroovyShell;

public class GroovyScriptManager {

  public static Object executeScript(String script) {
    GroovyShell shell = Aop.get(GroovyShell.class);
    return shell.evaluate(script);
  }

  /**
   * Execute a script located in the classpath.
   */
  @SuppressWarnings("unchecked")
  public static <T> T executeClasspathScript(String filename) {
    try (InputStream inputStream = ResourceUtil.getResourceAsStream(filename)) {
      if (inputStream != null) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
          String script = reader.lines().collect(Collectors.joining("\n"));
          return (T) executeScript(script);
        }
      } else {
        throw new IllegalArgumentException("Script file not found: " + filename);
      }
    } catch (Exception e) {
      throw new RuntimeException("Error executing Groovy script", e);
    }
  }
}

3. 创建 Groovy 脚本

src/main/resources/groovy 下创建一个名为 web_hello.groovy 的脚本文件,内容如下:

// web_hello.groovy
import com.litongjava.tio.http.common.HttpRequest
import com.litongjava.tio.http.common.HttpResponse
import com.litongjava.tio.boot.http.TioControllerContext
import com.litongjava.tio.utils.resp.RespVo

// 获取请求和响应对象
def request = TioControllerContext.getRequest()
def response = TioControllerContext.getResponse()

// 执行数据库查询
def sql = "select * from test_data where name=?"
println(sql)

// 设置响应对象
response.setJson(RespVo.ok(sql))
return response

4. 添加 HTTP 请求处理配置

添加HttpServerRequestHandlerConfig 类来调用 Groovy 脚本:

package com.litongjava.tio.web.hello.config;

import com.litongjava.jfinal.aop.annotation.AInitialization;
import com.litongjava.jfinal.aop.annotation.BeforeStartConfiguration;
import com.litongjava.tio.web.hello.GroovyScriptManager;
import com.litongjava.tio.http.server.handler.SimpleHttpRoutes;

@BeforeStartConfiguration
public class HttpServerRequestHandlerConfig {

    @AInitialization
    public void httpRoutes() {
        SimpleHttpRoutes simpleHttpRoutes = new SimpleHttpRoutes();
        simpleHttpRoutes.add("/hi", (request) -> {
            String filename = "groovy/web_hello.groovy";
            return GroovyScriptManager.executeClasspathScript(filename);
        });

        TioBootServer.me().setHttpRoutes(simpleHttpRoutes);
    }
}

这样,每当有 HTTP 请求到达 /hi 路由时,将执行 web_hello.groovy 脚本,并返回处理结果。这使得 Groovy 脚本能够在 Web 服务中处理请求

测试返回

response

{"data":"select * from test_data where name = ?","ok":true,"code":1,"msg":null}