阅读(4608) (0)

Micronaut 服务器事件

2023-02-23 11:27:27 更新

HTTP 服务器发出许多 Bean 事件,定义在 io.micronaut.runtime.server.event 包中,您可以为其编写侦听器。下表总结了这些:

表 1. 服务器事件
事件 描述

ServerStartupEvent

服务器完成启动时发出

ServerShutdownEvent

服务器关闭时发出

ServiceReadyEvent

在调用所有 ServerStartupEvent 侦听器并公开 EmbeddedServerInstance 后发出

ServiceStoppedEvent

在调用所有 ServerShutdownEvent 侦听器并公开 EmbeddedServerInstance 后发出

在 ServerStartupEvent 的侦听器中做大量工作会增加启动时间。

以下示例定义了一个侦听 ServerStartupEvent 的 ApplicationEventListener:

监听服务器启动事件

import io.micronaut.context.event.ApplicationEventListener;
...
@Singleton
public class StartupListener implements ApplicationEventListener<ServerStartupEvent> {
    @Override
    public void onApplicationEvent(ServerStartupEvent event) {
        // logic here
        ...
    }
}

或者,您也可以在接受 ServerStartupEvent 的任何 bean 的方法上使用 @EventListener 注释:

将@EventListener 与 ServerStartupEvent 一起使用

import io.micronaut.runtime.event.annotation.EventListener;
import io.micronaut.runtime.server.event.ServerStartupEvent;
import javax.inject.Singleton;
...
@Singleton
public class MyBean {

    @EventListener
    public void onStartup(ServerStartupEvent event) {
        // logic here
        ...
    }
}