Skip to content

tio-boot 入门示例 ​

创建新项目 ​

项目名称: tio-boot-web-hello

开源仓库地址:


添加依赖 ​

TioBoot 已在 Maven 中央仓库发布。

如果您使用 Java 21 进行开发,请在 pom.xml 文件中添加以下依赖项:

xml
<properties>
  <!-- 项目属性 -->
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>21</java.version>
  <maven.compiler.source>${java.version}</maven.compiler.source>
  <maven.compiler.target>${java.version}</maven.compiler.target>

  <!-- 版本属性 -->
  <lombok-version>1.18.44</lombok-version>
  <fastjson2.version>2.0.52</fastjson2.version>

  <hotswap-classloader.version>1.2.9</hotswap-classloader.version>
  <tio-boot.version>2.1.8</tio-boot.version>
  <jfinal-aop.version>1.4.0</jfinal-aop.version>


  <!-- 应用程序属性 -->
  <final.name>web-hello</final.name>
  <main.class>nexus.io.test.HelloApp</main.class>
</properties>

<dependencies>
  <!-- 日志框架 -->
  <dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.3.3</version>
  </dependency>

  <!-- Tio Boot 框架 -->
  <dependency>
    <groupId>nexus.io</groupId>
    <artifactId>tio-boot</artifactId>
    <version>${tio-boot.version}</version>
  </dependency>

  <!-- 热加载类加载器 -->
  <dependency>
    <groupId>nexus.io</groupId>
    <artifactId>hotswap-classloader</artifactId>
    <version>${hotswap-classloader.version}</version>
  </dependency>

  <!-- JFinal AOP -->
  <dependency>
    <groupId>nexus.io</groupId>
    <artifactId>jfinal-aop</artifactId>
    <version>${jfinal-aop.version}</version>
  </dependency>

  <!-- FastJSON2 用于 JSON 解析 -->
  <dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>${fastjson2.version}</version>
  </dependency>

  <!-- Lombok 用于简化代码 -->
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok-version}</version>
    <optional>true</optional>
    <scope>provided</scope>
  </dependency>

  <!-- JUnit 用于测试 -->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>
</dependencies>

<profiles>
  <!-- 开发环境配置 -->
  <profile>
    <id>development</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    <build>
      <plugins>
        <!-- Spring Boot Maven 插件 -->
        <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
          <version>2.7.18</version>
          <configuration>
            <fork>true</fork>
            <mainClass>${main.class}</mainClass>
            <excludeGroupIds>org.projectlombok</excludeGroupIds>
            <arguments>
              <argument>--mode=dev</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>

  <!-- 生产环境配置 -->
  <profile>
    <id>production</id>
    <build>
      <plugins>
        <!-- Spring Boot Maven 插件 -->
        <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
          <version>2.7.18</version>
          <configuration>
            <mainClass>${main.class}</mainClass>
            <excludeGroupIds>org.projectlombok</excludeGroupIds>
          </configuration>
          <executions>
            <execution>
              <goals>
                <goal>repackage</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

说明:

  • Properties 部分: 定义了关键的项目和版本属性,便于维护和管理依赖版本。
  • Dependencies 部分: 列出了所有必要的库和框架,涵盖日志、热加载、AOP、JSON 解析、HTTP 客户端等功能。
  • Profiles 部分: 配置了开发和生产环境的构建设置,确保在不同环境下应用程序的行为和性能优化。

Controller 和 Handler ​

TioBoot 支持两种类型的接口:Controller 和 Handler。了解它们的区别有助于您为应用程序选择最合适的方式。

区别 ​

  • Controller:

    • 支持自动请求参数封装。
    • 支持路由扫描(自动将 URL 映射到方法)。
    • 适用于一般用途的接口,开发更加便捷。
  • Handler:

    • 不支持自动请求参数封装,需要手动从 HttpRequest 中提取参数。
    • 不支持路由扫描,需要手动配置路由。
    • 性能更高,适用于对性能有高要求的系统级接口。

Controller 示例 ​

由于 Controller 需要通过扫描来被检测和加载,您需要在主应用程序类上添加 @AComponentScan 注解。

主应用程序类 (HelloApp.java):

java
package nexus.io.test;

import nexus.io.annotation.AComponentScan;
import nexus.io.tio.boot.TioApplication;

@AComponentScan
public class HelloApp {
  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    //TioApplicationWrapper.run(HelloApp.class, args);
    TioApplication.run(HelloApp.class, args);
    long end = System.currentTimeMillis();
    System.out.println((end - start) + "ms");
  }
}

说明:

  • @AComponentScan 注解启用了项目中 Controller 的自动扫描。
  • main 方法初始化 Tio 应用程序并输出启动时间,帮助您了解应用程序的启动性能。

Controller 类 (IndexController.java):

java
package nexus.io.test.controller;

import nexus.io.annotation.RequestPath;

@RequestPath("/")
public class IndexController {
  @RequestPath()
  public String index() {
    return "index";
  }
}

说明:

  • @RequestPath("/") 注解将此控制器映射到根 URL 路径。
  • index() 方法处理对根路径的 HTTP 请求并返回简单的字符串响应。

Handler 示例 ​

Handler 不需要扫描,因此主应用程序类中不需要 @AComponentScan 注解。

Handler 类 (HelloHandler.java):

java
package nexus.io.test.handler;

import java.util.HashMap;
import java.util.Map;

import nexus.io.model.body.RespBodyVo;
import nexus.io.tio.boot.http.TioRequestContext;
import nexus.io.tio.http.common.HttpRequest;
import nexus.io.tio.http.common.HttpResponse;

public class HelloHandler {
  public HttpResponse hello(HttpRequest request) {
    // 如有需要,手动提取参数
    // 例如:String param = request.getParam("key");

    Map<String, String> data = new HashMap<>();
    RespBodyVo respVo = RespBodyVo.ok(data);
    return TioRequestContext.getResponse().setJson(respVo);
  }
}

说明:

  • hello() 方法手动处理 HTTP 请求并构建响应。
  • 由于 Handler 不自动封装请求参数,您需要从 HttpRequest 中手动提取。
  • 使用 setJson() 方法将响应设置为 JSON 格式,确保客户端能够正确解析。

配置类 (WebHelloConfig.java):

java
import nexus.io.context.BootConfiguration;
import nexus.io.model.type.TioTypeReference;
import nexus.io.tio.boot.server.TioBootServer;
import nexus.io.tio.http.server.handler.IHttpRequestFunction;
import nexus.io.tio.http.server.router.HttpRequestFunctionRouter;
import nexus.io.tio.http.server.router.HttpRequestRouter;
import nexus.io.tio.web.hello.handler.HelloHandler;

public class WebHelloConfig implements BootConfiguration {

  public void config() {

    TioBootServer server = TioBootServer.me();
    HttpRequestRouter requestRouter = server.getRequestRouter();

    HelloHandler helloHandler = new HelloHandler();
    requestRouter.add("/hello", helloHandler::hello);
  }
}

说明:

  • 实现了 BootConfiguration 接口以设置自定义配置。
  • 手动添加了 /hello 路由并将其与 HelloHandler 的 hello() 方法关联,确保请求能够正确路由到对应的处理方法。
  • WebHelloConfig 不需要添加其他注解,已经在启动时将 WebHelloConfig 实例化并传递到 TioApplication,TioApplication 在启动时会执行 WebHelloConfig 的 config 方法

主应用程序类 (HelloApp.java):

java
package nexus.io.test;

import nexus.io.tio.boot.TioApplication;
import nexus.io.test.config.WebHelloConfig;

public class HelloApp {
  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    TioApplication.run(HelloApp.class, new WebHelloConfig(), args);
    long end = System.currentTimeMillis();
    System.out.println((end - start) + "ms");
  }
}

说明:

  • 使用 WebHelloConfig 中定义的自定义配置启动 Tio 应用程序。
  • 计算并输出启动时间,帮助评估应用程序的启动性能。

Lambda ​

如果你喜欢lambda,你可以这样写

java
package nexus.io.test;

import java.util.HashMap;
import java.util.Map;

import nexus.io.context.BootConfiguration;
import nexus.io.model.body.RespBodyVo;
import nexus.io.tio.boot.TioApplication;
import nexus.io.tio.boot.http.TioRequestContext;
import nexus.io.tio.boot.server.TioBootServer;
import nexus.io.tio.http.server.router.HttpRequestRouter;

public class HelloApp {

  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    TioApplication.run(HelloApp.class, new BootConfiguration() {

      @Override
      public void config() throws Exception {
        TioBootServer server = TioBootServer.me();
        HttpRequestRouter requestRouter = server.getRequestRouter();

        requestRouter.get("/hello", (request) -> {
          Map<String, String> data = new HashMap<>();
          RespBodyVo respVo = RespBodyVo.ok(data);
          return TioRequestContext.getResponse().setJson(respVo);
        });
      }
    }, args);
    long end = System.currentTimeMillis();
    System.out.println((end - start) + "ms");
  }
}

输出结果 ​

当您访问 http://localhost/hello 时,您将收到以下 JSON 响应:

json
{
  "data": {},
  "code": 1,
  "msg": null,
  "ok": true
}

运行应用程序 ​

使用 Spring Boot 插件 ​

使用 Spring Boot Maven 插件,以生产环境配置启动应用程序:

shell
mvn spring-boot:run -Pproduction

说明:

  • -Pproduction 参数激活了 pom.xml 中定义的生产环境配置。
  • 应用程序将以生产环境的设置启动,优化性能和资源使用。

测试应用程序 ​

  • 在浏览器中访问 http://localhost/,或使用 curl、Postman 等工具。
  • 您应该看到来自 IndexController 的输出 index。

打包应用程序 ​

将应用程序打包成可部署的 JAR 文件:

shell
mvn clean package -DskipTests -Dgpg.skip -Pproduction

推荐使用笔者开发的build工具 .build.txt

[win.env]
set JAVA_HOME=D:\java\jdk-21.0.6

[win.build]
mvn clean install -DskipTests -Dgpg.skip
mvn clean package -DskipTests -Dgpg.skip -Pproduction


[macos.build]
mvn clean install -DskipTests -Dgpg.skip
mvn clean package -DskipTests -Dgpg.skip -Pproduction

[linux.build]
mvn clean install -DskipTests -Dgpg.skip
mvn clean package -DskipTests -Dgpg.skip -Pproduction

执行命令.进行构建

build

说明:

  • clean:在构建前清理 target 目录,确保没有旧的构建文件影响新构建。
  • package:编译代码并打包成 JAR 文件,便于部署和分发。
  • -DskipTests:在构建过程中跳过测试,提高构建速度(仅在确认代码稳定时使用)。
  • -Pproduction:使用生产环境配置进行构建,确保生成的 JAR 文件适用于生产环境。

启动打包后的应用程序 ​

打包完成后,您可以使用生成的 JAR 文件启动应用程序:

shell
java -jar target/web-hello.jar

注意: 如果生成的 JAR 文件名称不同,请将 web-hello.jar 替换为实际的文件名。

说明:

  • 该命令使用 Java 运行时环境运行 JAR 文件,启动您的应用程序。
  • 应用程序将以生产环境的设置启动,确保在生产环境中的最佳性能和稳定性。

结论 ​

通过本指南,您已经:

  • 创建了一个新的 TioBoot 项目。
  • 添加了 Java 8 开发所需的依赖项。
  • 了解了 TioBoot 中 Controller 和 Handler 的区别。
  • 使用 Controller 和 Handler 实现了示例。
  • 为开发和生产环境配置了应用程序。
  • 打包并运行了您的应用程序。

提示:

  • 当您需要自动参数处理和路由扫描时,使用 Controller。
  • 当您需要更高的性能并且愿意手动处理请求参数时,使用 Handler。
  • 请在开发和生产模式下测试您的应用程序,以确保行为一致,避免在不同环境中出现意外问题。

祝您开发顺利!

MIT Licensed