微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Ballerina lang 的模块中创建服务

如何解决在 Ballerina lang 的模块中创建服务

我有以下文件结构:

│   Ballerina.toml
│   main.bal
│
├───modules
│   ├───http_listener
│   │       http_listener.bal
│   │       
│   └───question
│       │   .gitignore
│       │   question.bal
│       │   service.bal
│       │
│       └───tests
│               question_test.bal
│               service_test.bal
│
│
└───tests

main.bal 中包含以下服务:

import question_management.http_listener;
service / on http_listener:QuestionManagementListener {
    resource function get status() returns string {
        return "UP";
    }
}

http_listener 只是一个监听器:

import ballerina/http;

public listener http:Listener QuestionManagementListener = new(9095);

我面临的问题是 question/service.bal 中定义的服务不提供流量。服务定义如下:

import question_management.http_listener;

service /questions on http_listener:QuestionManagementListener {
    resource function get allQuestions() returns string {
        Question|error q = new Question("Test",["1","2","3","4","5"]);
        json[] qarray = [];
        if(!(q is error)) { qarray.push(q.toJson()); }
        return qarray.toJsonString();
    }
}

但是,当我启动程序时,只有 /status 端点按预期响应。这 questions/allQuestions 正在响应 404

no matching resource found for path : /questions/allQuestions,method : GET

如果我将服务从 question/service.bal 移至 main.bal/questions/allQuestions 将开始正常工作。但是,如果可能,我希望将我的服务定义放入它们自己的模块中。

解决方法

要初始化的模块需要在程序中直接或间接导入。这也适用于同一包中的模块。由于question_management.question没有直接导入到默认模块中,也没有直接导入到默认模块导入的模块中,所以question_management.question中的服务没有初始化或附加到监听器,这就是为什么会观察到这个错误.

可以使用导入前缀 _ 导入模块以将其包含在程序中,而无需使用其中的符号。这将导致模块被初始化,然后服务将被初始化并附加到侦听器 [1]。

在默认模块 (import question_management.question as _;) 中添加 main.bal 将导致 question_management.question 中的服务附加到侦听器,并且调用 /questions/allQuestions 应按预期工作。

[1] https://ballerina.io/learn/by-example/module-lifecycle

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。