1. 程式人生 > >Golang億級高並發實例(代碼可直接使用)

Golang億級高並發實例(代碼可直接使用)

bug urn print atan 可用 pri pre amp ola

可以直接拿去當成一個庫來用

舉例

package main
import "your/path/to/.../Concurrence"

//定義一個實現Job接口的數據
type Score struct {
    Num int
}
//定義對數據的處理
func (s *Score) Do() {
    fmt.Println("num:", s.Num)
    time.Sleep(1 * 1 * time.Second)
}

func main() {
    num := 100 * 100 * 20
    // debug.SetMaxThreads(num + 1000) //設置最大線程數
    // 註冊工作池,傳入任務
    // 參數1 worker並發個數
    p := NewWorkerPool(num)
    p.Run()

    //寫入一億條數據
    datanum := 100 * 100 * 100 * 100
    go func() {
        for i := 1; i <= datanum; i++ {
            sc := &Score{Num: i}
            p.JobQueue <- sc //數據傳進去會被自動執行Do()方法,具體對數據的處理自己在Do()方法中定義
        }
    }()

//循環打印輸出當前進程的Goroutine 個數
    for {
        fmt.Println("runtime.NumGoroutine() :", runtime.NumGoroutine())
        time.Sleep(2 * time.Second)
    }

}

Concurrence.go

package Concurrence

import "fmt"

// --------------------------- Job ---------------------
type Job interface {
    Do()
}

// --------------------------- Worker ---------------------
type Worker struct {
    JobQueue chan Job
}

func NewWorker() Worker {
    return Worker{JobQueue: make(chan Job)}
}
func (w Worker) Run(wq chan chan Job) {
    go func() {
        for {
            wq <- w.JobQueue
            select {
            case job := <-w.JobQueue:
                job.Do()
            }
        }
    }()
}

// --------------------------- WorkerPool ---------------------
type WorkerPool struct {
    workerlen   int
    JobQueue    chan Job
    WorkerQueue chan chan Job
}

func NewWorkerPool(workerlen int) *WorkerPool {
    return &WorkerPool{
        workerlen:   workerlen,
        JobQueue:    make(chan Job),
        WorkerQueue: make(chan chan Job, workerlen),
    }
}
func (wp *WorkerPool) Run() {
    fmt.Println("初始化worker")
    //初始化worker
    for i := 0; i < wp.workerlen; i++ {
        worker := NewWorker()
        worker.Run(wp.WorkerQueue)
    }
    // 循環獲取可用的worker,往worker中寫job
    go func() {
        for {
            select {
            case job := <-wp.JobQueue:
                worker := <-wp.WorkerQueue
                worker <- job
            }
        }
    }()
}

// --------------- 使用 --------------------
/*
type Score struct {
    Num int
}

func (s *Score) Do() {
    fmt.Println("num:", s.Num)
    time.Sleep(1 * 1 * time.Second)
}

func main() {
    num := 100 * 100 * 20
    // debug.SetMaxThreads(num + 1000) //設置最大線程數
    // 註冊工作池,傳入任務
    // 參數1 worker並發個數
    p := NewWorkerPool(num)
    p.Run()
    datanum := 100 * 100 * 100 * 100
    go func() {
        for i := 1; i <= datanum; i++ {
            sc := &Score{Num: i}
            p.JobQueue <- sc
        }
    }()

    for {
        fmt.Println("runtime.NumGoroutine() :", runtime.NumGoroutine())
        time.Sleep(2 * time.Second)
    }

}
*/

Golang億級高並發實例(代碼可直接使用)