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

时间:2019-10-08 12:07:19

标签: ballerina

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

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

1 个答案:

答案 0 :(得分: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