Ballerina V 1.0 - 将数据库连接保存在单独的文件中

Ballerina V 1.0 - Keep DB connection in a separate file

在我的芭蕾舞项目中,我在同一个 .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);
    }
}

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

如果您想在多个 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