Worker & Tác vụ nền
Tổng quan
Fountain xem các tác vụ chạy nền là những thành phần thực thi cốt lõi (runnable) và được điều phối bởi singleton Fountain. Thứ tự khởi tạo sẽ là: Invoker → Job → Cron → AppInstance → Auxiliary.
- Invoker — các bước khởi tạo chạy một lần trước khi server hoạt động (ví dụ: kết nối database).
- Job — các đơn vị xử lý nền dạng
JobInstance; xem thêm tạifjob. - Cron — các tác vụ chạy theo lịch; xem thêm tại
fcron. - Worker pool — cơ chế chạy song song và xử lý đồng thời thông qua
fgo.
Ví dụ
Một job runnable được tích hợp vào framework:
go
/* !!
* File: main.go
* File Created: Tuesday, 28th June 2022 4:24:43 pm
* Author: Kim Ericko ([email protected])
* -----
* Last Modified: Thursday, 30th June 2022 5:12:31 pm
* Modified By: Kim Ericko ([email protected])
* -----
* Copyright 2022 Soludian, soludian.com
* All rights reserved.
*
* Licensed under the SOLUDIAN TECHNOLOGY SOLUTION CO., LTD Software License Agreement.
* Unauthorized use, reproduction, or distribution is prohibited (the "License");
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* [email protected] / https://www.soludian.com/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -----
*
* HISTORY:
*
* Date By Comments
* ---------- --- ---------------------------------------------------------
*/
package main
import (
"errors"
"log"
"os"
"time"
"gitlab.soludian.com/soludian/fountain"
"gitlab.soludian.com/soludian/fountain/constants"
"gitlab.soludian.com/soludian/fountain/libs/ftasker/fjob"
"gitlab.soludian.com/soludian/fountain/libs/ftracer"
)
// export FOUNTAIN_DEBUG_MODE=true && go run main.go --job=job1 --config=config.toml
func main() {
os.Setenv(constants.KFountainJobNameEnvKey, "job1") // #nosec G104
fountain.WithHang(true).WithJobs(fjob.Job("job1", job1), fjob.Job("job2", job2)).Serving()
}
func job2(ctx fjob.Context) error {
log.Println("Job 2 sleeping...")
time.Sleep(10 * time.Second)
log.Println("i am error job runner, traceId: ", ftracer.ExtractTraceID(ctx.Ctx))
return errors.New("i am error")
}
func job1(ctx fjob.Context) error {
log.Println("i am job runner, traceId: ", ftracer.ExtractTraceID(ctx.Ctx))
return nil
}Xem thêm
- Tài liệu tham khảo:
fjob,fcron,fgo - Runnable — các interface
AppInstance,Invoker,JobInstance - Danh sách ví dụ