搜尋
首頁後端開發GolangGo 中的 Redis 隊列和 Cron

Go 中的 Redis 隊列和 Cron

Dec 31, 2024 am 04:40 AM

Redis Queue and Cron in Go

原文在這裡

在本教程中,我們將與佇列互動並將其放入 Redis 伺服器
使用 github.com/hibiken/asynq 套件並為
建立調度程序 使用 github.com/robfig/cron 套件的排程任務。這一步一步
指南解釋如何設定隊列、安排任務以及優雅地處理
關閉。

初始化模組

先為專案建立一個新的 Go 模組:

go mod init learn_queue_and_cron

創建 cron.go

cron.go 檔案負責在特定時間排程和執行任務
間隔。下面是實作:

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/robfig/cron/v3"
)

func runCron(c *cron.Cron) {

    // Schedule a task to run every minute
    _, err := c.AddFunc("@every 1m", func() {
        fmt.Printf("Task executed every minute at: %v \n", time.Now().Local())
    })
    if err != nil {
        log.Fatal(err)
    }

    // Start the cron scheduler
    c.Start()
    log.Println("Cron scheduler started")

    // Keep the main goroutine running
    select {}
}

此程式碼安排任務每分鐘運行一次並保持應用程式運行
確保調度程序連續工作。

創建queue.go

queue.go 檔案使用 Asynq 管理任務處理。程式碼如下:

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"

    "github.com/hibiken/asynq"
)

func runQueue(server *asynq.Server) {
    mux := asynq.NewServeMux()
    mux.HandleFunc("send_email", emailHandler)
    mux.HandleFunc("generate_report", reportHandler)

    if err := server.Run(mux); err != nil {
        log.Fatalf("Failed to run Asynq server: %v", err)
    }
}

func emailHandler(ctx context.Context, task *asynq.Task) error {
    var payload struct {
        To string `json:"to"`
    }
    if err := json.Unmarshal(task.Payload(), &payload); err != nil {
        return fmt.Errorf("failed to unmarshal payload: %w", err)
    }
    fmt.Printf("Sending email to: %s\n", payload.To)
    return nil
}

func reportHandler(ctx context.Context, task *asynq.Task) error {
    var payload struct {
        ReportID int `json:"report_id"`
    }
    if err := json.Unmarshal(task.Payload(), &payload); err != nil {
        return fmt.Errorf("failed to unmarshal payload: %w", err)
    }
    fmt.Printf("Generating report for ID: %d\n", payload.ReportID)
    return nil
}

解釋

  • Handlers: emailHandler 和 reportHandler 透過解析處理任務 它們的有效負載並執行相應的操作。
  • 任務佇列:定義了「send_email」和「generate_report」等任務 並透過Asynq的任務佇列進行處理。

建立router.go

router.go 檔案設定 HTTP 端點來將任務排入佇列:

package main

import (
    "encoding/json"
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/hibiken/asynq"
)

func setupRouter(client *asynq.Client) *gin.Engine {
    r := gin.Default()

    r.POST("/enqueue/email", func(c *gin.Context) {
        var payload struct {
            To string `json:"to"`
        }
        if err := c.ShouldBindJSON(&payload); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
            return
        }

        jsonPayload, err := json.Marshal(payload)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal payload"})
            return
        }

        task := asynq.NewTask("send_email", jsonPayload)
        _, err = client.Enqueue(task)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to enqueue task"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"message": "Email job enqueued"})
    })

    r.POST("/enqueue/report", func(c *gin.Context) {
        var payload struct {
            ReportID int `json:"report_id"`
        }
        if err := c.ShouldBindJSON(&payload); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
            return
        }

        jsonPayload, err := json.Marshal(payload)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal payload"})
            return
        }

        task := asynq.NewTask("generate_report", jsonPayload)
        _, err = client.Enqueue(task)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to enqueue task"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"message": "Report job enqueued"})
    })

    return r
}

此程式碼使用 Gin 框架公開兩個端點以用於排隊任務。

建立main.go

main.go 檔案將所有內容整合在一起:

package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"

    "github.com/hibiken/asynq"
    "github.com/robfig/cron/v3"
)

func main() {
    c := cron.New()

    server := asynq.NewServer(
        asynq.RedisClientOpt{Addr: "localhost:6379"},
        asynq.Config{
            Concurrency: 10,
        },
    )

    client := asynq.NewClient(asynq.RedisClientOpt{Addr: "localhost:6379"})
    defer client.Close()

    router := setupRouter(client)

    httpServer := &http.Server{
        Addr:    ":8080",
        Handler: router,
    }

    // Prepare shutdown context
    ctx, stop := context.WithCancel(context.Background())
    defer stop()
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, os.Interrupt, syscall.SIGTERM)

    go runQueue(server)
    go runCron(c)
    go func() {
        if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("Failed to run HTTP server: %v", err)
        }
    }()

    appShutdown(ctx, httpServer, c, server, quit)
}

func appShutdown(ctx context.Context, httpServer *http.Server, c *cron.Cron, server *asynq.Server, quit chan os.Signal) {
    // Wait for termination signal
    



<p>此檔案結合了佇列、cron、HTTP 伺服器和關閉邏輯。 </p>

<h2>
  
  
  安裝依賴項
</h2>

<p>安裝所有必要的依賴項:<br>
</p>

<pre class="brush:php;toolbar:false">go mod tidy

建置並運行應用程式

使用以下命令建置並執行應用程式:

go build -o run *.go && ./run

測試應用程式

存取以下端點將任務排隊:

  • http://localhost:8080/enqueue/email
  • http://localhost:8080/enqueue/report

觀察終端的任務執行日誌。

規範網址

欲了解更多詳細信息,請訪問我博客上的原始帖子。

以上是Go 中的 Redis 隊列和 Cron的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
實施靜音和鎖以尋求線程安全性實施靜音和鎖以尋求線程安全性May 05, 2025 am 12:18 AM

在Go中,使用互斥鎖和鎖是確保線程安全的關鍵。 1)使用sync.Mutex進行互斥訪問,2)使用sync.RWMutex處理讀寫操作,3)使用原子操作進行性能優化。掌握這些工具及其使用技巧對於編寫高效、可靠的並發程序至關重要。

基準測試和分析並發GO代碼基準測試和分析並發GO代碼May 05, 2025 am 12:18 AM

如何優化並發Go代碼的性能?使用Go的內置工具如gotest、gobench和pprof進行基準測試和性能分析。 1)使用testing包編寫基準測試,評估並發函數的執行速度。 2)通過pprof工具進行性能分析,識別程序中的瓶頸。 3)調整垃圾收集設置以減少其對性能的影響。 4)優化通道操作和限制goroutine數量以提高效率。通過持續的基準測試和性能分析,可以有效提升並發Go代碼的性能。

並發程序中的錯誤處理:避免常見的陷阱並發程序中的錯誤處理:避免常見的陷阱May 05, 2025 am 12:17 AM

避免並發Go程序中錯誤處理的常見陷阱的方法包括:1.確保錯誤傳播,2.處理超時,3.聚合錯誤,4.使用上下文管理,5.錯誤包裝,6.日誌記錄,7.測試。這些策略有助於有效處理並發環境中的錯誤。

隱式接口實現:鴨打字的力量隱式接口實現:鴨打字的力量May 05, 2025 am 12:14 AM

IndimitInterfaceImplementationingingoembodiesducktybybyallowingTypestoSatoSatiSatiSatiSatiSatiSatsatSatiSatplicesWithouTexpliclIctDeclaration.1)itpromotesflemotesflexibility andmodularitybybyfocusingion.2)挑戰挑戰InclocteSincludeUpdatingMethodSignateSignatiSantTrackingImplections.3)工具li

進行錯誤處理:最佳實踐和模式進行錯誤處理:最佳實踐和模式May 04, 2025 am 12:19 AM

在Go編程中,有效管理錯誤的方法包括:1)使用錯誤值而非異常,2)採用錯誤包裝技術,3)定義自定義錯誤類型,4)復用錯誤值以提高性能,5)謹慎使用panic和recover,6)確保錯誤消息清晰且一致,7)記錄錯誤處理策略,8)將錯誤視為一等公民,9)使用錯誤通道處理異步錯誤。這些做法和模式有助於編寫更健壯、可維護和高效的代碼。

您如何在GO中實施並發?您如何在GO中實施並發?May 04, 2025 am 12:13 AM

在Go中實現並發可以通過使用goroutines和channels來實現。 1)使用goroutines來並行執行任務,如示例中同時享受音樂和觀察朋友。 2)通過channels在goroutines之間安全傳遞數據,如生產者和消費者模式。 3)避免過度使用goroutines和死鎖,合理設計系統以優化並發程序。

在GO中構建並發數據結構在GO中構建並發數據結構May 04, 2025 am 12:09 AM

Gooffersmultipleapproachesforbuildingconcurrentdatastructures,includingmutexes,channels,andatomicoperations.1)Mutexesprovidesimplethreadsafetybutcancauseperformancebottlenecks.2)Channelsofferscalabilitybutmayblockiffullorempty.3)Atomicoperationsareef

將GO的錯誤處理與其他編程語言進行比較將GO的錯誤處理與其他編程語言進行比較May 04, 2025 am 12:09 AM

go'serrorhandlingisexplicit,治療eRROSASRETRATERTHANEXCEPTIONS,與pythonandjava.1)go'sapphifeensuresererrawaresserrorawarenessbutcanleadtoverbosecode.2)pythonandjavauseexeexceptionseforforforforforcleanerCodebutmaymobisserrors.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具