Балерина V 1.0 - Хранить соединение с БД в отдельном файле - PullRequest
1 голос
/ 08 октября 2019

В своем проекте балерины я создал соединение с БД и внедрил службы в одном и том же файле .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 Ответ

1 голос
/ 09 октября 2019

Если вы хотите управлять своим кодом в нескольких файлах bal, вам нужно структурировать свой код с помощью проекта Ballerina. Пожалуйста, обратитесь к этому руководству для получения дополнительной информации.

// 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
...