You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非默认模块定义的Ballerina服务与监听器无法运行,如何修复?

问题:非默认模块中的Ballerina HTTP服务无法启动

我有一个Ballerina包,其中REST API和HTTP监听器定义在非默认模块(mod)中。使用bal run运行包时,仅输出main函数的"Hello, World!"后程序就停止,HTTP服务无法正常响应请求。

包结构

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

各文件内容

Ballerina.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时,默认会运行包的默认模块(根目录下main.bal所在模块),该模块的main函数执行完毕后程序直接退出,不会自动加载非默认模块中的代码(包括HTTP监听器和服务)。

解决方法

有两种可行方式让非默认模块中的HTTP服务正常运行:

方法一:直接运行指定模块

使用bal run命令时指定非默认模块名称,直接加载该模块代码并启动HTTP监听器:

bal run mod

执行后会输出Welcome!,程序保持运行状态,此时可访问http://localhost:8080/greeting获取响应。

方法二:修改默认模块,导入并依赖非默认模块

修改根目录下的main.bal,导入非默认模块并让程序持续运行:

import ballerina/io;
import ballerina/runtime;
// 导入非默认模块,路径格式为 org/package.module
import testorg/restapi.mod;

public function main() {
    io:println("Hello, World!");
    // 阻止程序在main函数执行完后退出
    runtime:wait();
}

修改后执行bal run,程序会输出Hello, World!和Welcome!并持续运行,HTTP服务可正常响应请求。


内容的提问来源于stack exchange,提问作者Nadeeshan Dissanayake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:33:30