1

简单的问题。是否可以在没有 的情况下创建端点@Endpoint?我想通过文件并根据其上下文的内容创建相当动态的端点。

谢谢!


更新我的想法。我想创建一个插件系统之类的东西,以使我的应用程序更易于维护和未来的功能。

值得一提的是,我正在将 Micronaut 与 Kotlin 一起使用。现在我有固定定义的端点,它与我的命令脚本相匹配。

我的描述文件将在/src/main/resources

在此处输入图像描述

我有以下示例描述文件它的外观。

ENDPOINT: GET /myapi/customendpoint/version
COMMAND: """
#!/usr/bin/env bash

# This will be executed via SSH and streamed to stdout for further handling
echo "1.0.0"
"""
# This is a template JSON which will generate a JSON as production on the endpoint
OUTPUT: """
{
  "version": "Server version: $RESULT"
}
"""

我想让它如何与应用程序一起工作。

import io.micronaut.docs.context.events.SampleEvent
import io.micronaut.context.event.StartupEvent
import io.micronaut.context.event.ShutdownEvent
import io.micronaut.runtime.event.annotation.EventListener

@Singleton
class SampleEventListener {
    /*var invocationCounter = 0

    @EventListener
    internal fun onSampleEvent(event: SampleEvent) {
        invocationCounter++
    }*/

    @EventListener
    internal fun onStartupEvent(event: StartupEvent) {
        // 1. I read all my description files
        // 2. Parse them (for what I created a parser)
        // 3. Now the tricky part, how to add those information to Micronaut Runtime
        
        val do = MyDescription() // After I parsed
        // Would be awesome if it is that simple! :)
        Micronaut.addEndpoint(
          do.getEndpoint(), do.getHttpOption(),
          MyCustomRequestHandler(do.getCommand()) // Maybe there is a base class for inheritance?
        )
    }

    @EventListener
    internal fun onShutdownEvent(event: ShutdownEvent) {
        // shutdown logic here
    }
}
4

1 回答 1

1

您可以创建一个自定义RouteBuilder,将在运行时注册您的自定义端点:

@Singleton
class CustomRouteBuilder extends DefaultRouteBuilder {

    @PostConstruct
    fun initRoutes() {
        val do = MyDescription();
        val method = do.getMethod();
        val routeUri = do.getEndpoint();
        val routeHandle = MethodExecutionHandle<Object, Object>() {
            // implement the 'MethodExecutionHandle' in a suitable manner to invoke the 'do.getCommand()'
        };
        buildRoute(HttpMethod.parse(method), routeUri, routeHandle);
    }
}

请注意,虽然这仍然可行,但最好考虑另一种扩展路径,因为该解决方案违背了作为 AOT 编译框架的整个Micronaut哲学。

于 2021-11-09T11:07:01.880 回答