服务器监听器文档

1. 实现自定义服务器监听器

为了在 Tio-Boot 项目中创建一个自定义的服务器监听器,我们可以通过实现 TioBootServerListener 接口来拦截服务器启动的关键点,并添加一些自定义的启动逻辑。下面是一个实现自定义监听器的示例,MyServerListener 类负责在服务器启动后执行额外的操作。

示例代码

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

import com.litongjava.hotswap.watcher.HotSwapWatcher;
import com.litongjava.hotswap.wrapper.tio.boot.TioBootArgument;
import com.litongjava.hotswap.wrapper.tio.boot.TioBootRestartServer;
import com.litongjava.jfinal.aop.Aop;
import com.litongjava.jfinal.aop.AopManager;
import com.litongjava.tio.boot.constatns.ConfigKeys;
import com.litongjava.tio.boot.context.Context;
import com.litongjava.tio.boot.server.TioBootServerListener;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyServerListener implements TioBootServerListener {

  protected static volatile HotSwapWatcher hotSwapWatcher;

  /**
   * 在服务器启动前调用
   */
  @Override
  public void boforeStart(Class<?>[] primarySources, String[] args) {
    // 可以在此处添加启动前的逻辑,例如参数校验或初始化操作
  }

  /**
   * 服务器启动后调用
   */
  @Override
  public void afterStarted(Class<?>[] primarySources, String[] args, Context context) {

  }
}

说明:

  1. boforeStart() 方法:可用于在服务器启动前执行操作,当前未添加任何逻辑。
  2. afterStarted() 方法:在服务器启动后执行,如果当前环境为开发环境 (dev),则启动 HotSwapWatcher 来监控类文件的变化,从而在开发阶段实现类热加载。

2. 注册服务器监听器

为了使自定义的监听器能够生效,我们需要在应用启动前将它注册到 Aop 容器中。通过创建 TioBootServerListenerConfig 类,并在启动时将监听器注入 Aop 容器,可以确保 MyServerListener 能够在应用启动过程中被正确调用。

注册监听器代码

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

import com.litongjava.jfinal.aop.annotation.Bean;
import com.litongjava.jfinal.aop.annotation.BeforeStartConfiguration;
import com.litongjava.tio.boot.server.TioBootServerListener;

@AConfiguration
public class TioBootServerListenerConfig {

  @AInitialization
  public void tioBootServerListener() {
    // 注册自定义监听器
    TioBootServer.me().setTioBootServerListener(new MyServerListener());
  }
}

说明:

  1. BeforeStartConfiguration 注解:用于在应用启动前进行配置操作,这里用于注册服务器监听器。
  2. @AInitialization 注解:用于将 初始化配置,使其能够在启动时被调用。

3. 总结

通过实现 TioBootServerListener 接口并将自定义监听器注册到 Aop 容器中,可以在 Tio-Boot 项目中定制服务器启动过程中的行为。

这份文档介绍了如何实现和注册服务器监听器的完整流程,并为开发者提供了灵活的方式来控制服务器启动行为。