【问题标题】:Ballerina V 1.0 - Keep DB connection in a separate fileBallerina V 1.0 - 将数据库连接保存在单独的文件中
【发布时间】:2019-10-08 12:07:19
【问题描述】:

在我的芭蕾舞演员项目中,我在同一个 .bal 文件中完成了数据库连接创建和服务实现。

import ballerina/config;
import ballerina/http;
import ballerina/io;
import ballerina/jsonutils;
import ballerinax/java.jdbc;

jdbc:Client studentMgtDB = new ({
    url: "jdbc:mysql://" + config:getAsString("student.jdbc.dbHost") + ":" +      config:getAsString("student.jdbc.dbPort") + "/" + config:getAsString("student.jdbc.db"),
    username: config:getAsString("student.jdbc.username"),
    password: config:getAsString("student.jdbc.password"),
    poolOptions: {maximumPoolSize: 5},
    dbOptions: {useSSL: false}
});

type Student record {
    int std_id;
    string name;
    int age;
    string address;
};

listener http:Listener studentMgtServiceListener = new (9090);

@http:ServiceConfig {
    basePath: "/students"
}

service studentMgtService on studentMgtServiceListener {

    @http:ResourceConfig {
        methods: ["GET"],
        path: "/"
    }
    resource function getStudent(http:Caller caller, http:Request req) {
        var selectStudents = studentMgtDB->select("SELECT * FROM student", Student);
        http:Response response = new;
        if (selectStudents is table<Student>) {
            response.statusCode = 200;
        } else {
            response.statusCode = 500;
        }
        checkpanic caller->respond(response);
    }
}

我只想将数据库连接部分移动到单独的文件中,因为这样更便于维护。那么最好的方法是什么?

【问题讨论】:

    标签: ballerina


    【解决方案1】:

    如果您想在多个 bal 文件中管理您的代码,您需要使用 Ballerina 项目来构建您的代码。请参阅this guide 了解更多信息。

    // Create a new project with the name 'student_mgt_proj'
    $ ballerina new studentmgt_proj
    
    $ cd student_mgt_proj
    
    // Create a new module named 'studentmgt'
    $ ballerina add studentmgt
    

    现在将所有 bal 文件添加到 src/studentmgt 目录。

    // Build the executable service jar
    $ ballerina build studentmgt
    
    // You can also use java -jar studentmgt.jar, if you are using Java 8
    $ ballerina run studentmgt.jar
    

    【讨论】:

    • 谢谢。我也在尝试这个。现在我在 studentmgt 模块中有 2 个 .bal 文件作为 dbConn.bal 和 student.bal。在 dbConn.bal 中,我创建了一个返回 jdbc:Client 的函数。当我在 student.bal 中调用该方法时,dbConn.bal 中出现编译错误,作为“未记录的返回参数”。我在这里犯了什么错误?
    • 将此问题作为另一个问题提出:stackoverflow.com/questions/58300618/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2015-02-24
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    相关资源
    最近更新 更多