基於golang channel的輕量級異步任務分發器

項目地址:https://github.com/chenhg5/go...git

有時候咱們爲了更好的利用計算機資源,能夠把一些耗時長的任務隊列化異步執行。舉個對應簡單的生活中例子就是大多數餐廳裏面點菜都是先找地方作,看了菜單選好菜以後找服務員點菜,此時再等待菜作好送上來。這裏餐廳廚房就是計算機的底層資源,菜就是待執行的任務,而服務員就是咱們的go channel。github

關於消息隊列有不少好用的框架,如nsq,nats,kafka等等。但有時咱們只須要輕量級的異步任務工具,而不須要太過於"複雜"的框架相對於咱們的需求來講。因而借鑑一些項目框架,作了一個小小的封裝。golang

go-task的使用很簡單,只須要初始化一個任務處理器,而後往處理器裏面添加任務,而後處理器就會異步地去執行了。shell

舉餐廳的例子,代碼以下:框架

package main

import (
    "runtime"
    "fmt"
    "time"
    "github.com/chenhg5/go-task"
    "strconv"
)

func main() {

    // init
    task.InitTaskReceiver(runtime.NumCPU())

    // 有十我的同時點菜
    for i := 0; i < 10; i++ {
        task.AddTask(task.NewTask(
            map[string]interface{}{
                "user" : strconv.Itoa(i),
            },  // 參數
            []task.FacFunc{ordering, cooking, deliverying}, // 任務列表
            -1), // -1表明任務不超時
        )
    }

    time.Sleep(time.Second * 50)
}

// 下單任務
func ordering(uuid string, param map[string]interface{}) (string, error) {
    fmt.Println("user " + param["user"].(string) + " is ordering")
    time.Sleep(time.Second * 1)
    return uuid, nil
}

// 作菜任務
func cooking(uuid string, param map[string]interface{}) (string, error) {
    fmt.Println("user " + param["user"].(string) + " is cooking")
    time.Sleep(time.Second * 1)
    return uuid, nil
}

// 配送任務
func deliverying(uuid string, param map[string]interface{}) (string, error) {
    fmt.Println("user " + param["user"].(string) + " is deliverying")
    time.Sleep(time.Second * 1)
    return uuid, nil
}

跑一遍,就會看到:異步

user 0 is ordering
user 1 is ordering
user 2 is ordering
user 3 is ordering
user 4 is ordering
user 5 is ordering
user 6 is ordering
user 7 is ordering
user 0 is cooking
user 2 is cooking
user 1 is cooking
user 3 is cooking
user 4 is cooking
user 5 is cooking
user 6 is cooking
user 7 is cooking
user 0 is deliverying
user 1 is deliverying
user 2 is deliverying
user 3 is deliverying
user 6 is deliverying
user 7 is deliverying
user 5 is deliverying
user 4 is deliverying
user 8 is ordering
user 9 is ordering
user 8 is cooking
user 9 is cooking
user 9 is deliverying
user 8 is deliverying
相關文章
相關標籤/搜索