当 Ballerina 程序运行时,在非默认模块中定义的服务和侦听器不起作用

A service and a listener defined in a non-default module do not work when the Ballerina program runs

提问人:Nadeeshan Dissanayake 提问时间:11/17/2023 更新时间:11/17/2023 访问量:19

问:

我有一个 Ballerina 包,其中有一个 rest API 和一个在包中的另一个模块中定义的侦听器。包结构和芭蕾舞女演员代码如下。

restapi % tree     
.
├── Ballerina.toml
├── main.bal
└── modules
    └── mod
        ├── Module.md
        └── mod.bal

芭蕾舞女演员.toml

[package]
org = "testorg"
name = "restapi"
version = "0.1.0"
distribution = "2201.8.2"

[build-options]
observabilityIncluded = true

main.bal

import ballerina/io;

public function main() {
    io:println("Hello, World!");
}

mod.bal (英语)

import ballerina/http;
import ballerina/io;

listener http:Listener httpListener = new (8080);

string welcomeMessage = "Welcome!";

function init() returns error? {
    io:println(welcomeMessage);
}

service / on httpListener {
    resource function get greeting() returns string {
        return "Hello, World!";
    }
}

当我使用 运行上述包时,它会运行并停止给出以下输出。该服务似乎不起作用,并且不响应请求。bal run

restapi % bal run
Compiling source
        testorg/restapi:0.1.0

Running executable

Hello, World!

应该怎么做才能使服务正常工作?

导入 服务 模块 监听器 Ballerina

评论


答:

1赞 Nadeeshan Dissanayake 11/17/2023 #1

我们需要从包的默认模块中导入非默认模块来运行上述服务。要初始化非默认模块(运行函数并处理侦听器),非默认模块需要由 Ballerina 包的默认模块导入。由于我们在默认模块中没有将其用于任何其他目的,因此我们可以使用 import 前缀 .init_

因此,需要按如下方式编辑该文件。main.bal

import ballerina/io;
import restapi.mod as _;

public function main() {
    io:println("Hello, World!");
}

它现在将运行服务并提供输出。

restapi % bal run
Compiling source
        testorg/restapi:0.1.0

Running executable

Welcome!
Hello, World!