使用 Tio-Http-Server 搭建简单的 HTTP 服务

如果你的项目无需 WebSocket 功能,且对性能有较高要求,那么可以考虑使用 tio-http-server 作为 HTTP 服务的基础。tio-http-server 是一款高性能的 Java HTTP 服务框架,专为满足低延迟、高并发场景而设计。本文将介绍如何使用 tio-http-server 搭建一个简单的 HTTP 服务。

添加依赖

首先,在你的 Maven 项目中添加 tio-http-server 的依赖:

<dependency>
  <groupId>com.litongjava</groupId>
  <artifactId>tio-http-server</artifactId>
  <version>${tio.version}</version>
</dependency>

编写控制器

接下来,我们需要编写一个简单的控制器类 IndexController,用来处理不同的 HTTP 请求。在这个例子中,控制器中包含了几个基本的接口:indexloginexception

package demo.controller;

import com.litongjava.tio.http.common.HttpRequest;
import com.litongjava.tio.http.common.HttpResponse;
import com.litongjava.tio.http.server.util.Resps;

public class IndexController {

  // 处理根路径的请求
  public HttpResponse index(HttpRequest request) {
    return Resps.txt(request, "index");
  }

  // 处理登录请求
  public HttpResponse login(HttpRequest request) {
    return Resps.txt(request, "login");
  }

  // 处理异常请求,演示抛出异常
  public HttpResponse exception(HttpRequest request) {
    throw new RuntimeException("error");
  }
}

编写启动类

然后,编写一个启动类 DemoHttpServer,该类主要负责配置服务器并启动 HTTP 服务。

package demo;

import java.io.IOException;

import com.litongjava.tio.http.common.HttpConfig;
import com.litongjava.tio.http.server.HttpServerStarter;
import com.litongjava.tio.http.server.handler.HttpRoutes;
import com.litongjava.tio.http.server.handler.SimpleHttpRoutes;

import demo.controller.IndexController;

public class DemoHttpServer {

  public static void main(String[] args) throws IOException {

    // 实例化 Controller
    IndexController controller = new IndexController();

    // 手动添加路由
    HttpRoutes simpleHttpRoutes = new SimpleHttpRoutes();
    simpleHttpRoutes.add("/", controller::index);     // 根路径处理
    simpleHttpRoutes.add("/login", controller::login); // 登录路径处理
    simpleHttpRoutes.add("/exception", controller::exception); // 异常演示

    // 添加 JSON 返回类型的路由
    simpleHttpRoutes.add("/json", (request) -> {
      return new HttpResponse(request).setJson(RespVo.ok("ok"));
    });

    // 配置服务器
    HttpConfig httpConfig = new HttpConfig(80, null, null, null);
    HttpServerStarter httpServerStarter = new HttpServerStarter(httpConfig, simpleHttpRoutes);

    // 启动服务器
    httpServerStarter.start();
  }
}

运行

编写完以上代码后,运行 DemoHttpServermain 方法即可启动 HTTP 服务。此时,你可以通过浏览器访问 http://localhost/ 查看根路径的响应,或通过 http://localhost/login 查看登录页面的响应。如果访问 http://localhost/exception,将会抛出一个异常,用于演示错误处理。

总结

通过本文的介绍,我们了解了如何使用 tio-http-server 搭建一个简单的 HTTP 服务。这个框架轻量且高效,适合对性能有较高要求的项目。你可以根据需要进一步扩展路由和功能,例如支持 JSON 返回类型、文件上传等。