主要参考 https://github.com/yaodongen/delay-queue

package main

import (
    "context"
    "fmt"
    "github.com/go-redis/redis/v8"
    delay "github.com/yaodongen/delay-queue"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    ctx := context.Background()
    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        DB:       1,
        PoolSize: 100, // 连接池大小
    })
    // producer  https://github.com/yaodongen/delay-queue
    // 对应的key, value, 延迟执行的时间, 最大的TTL生存时间
    err := delay.AddToQueue(ctx, rdb, "key", "123", 15, 86400)
    err = delay.AddToQueue(ctx, rdb, "key", "456", 20, 86400)
    err = delay.AddToQueue(ctx, rdb, "key", "789", 30, 86400)
    if err != nil {
        // your own logic
    }
    fmt.Println(time.Now())
    // consumer
    go func() {
        resCh, errCh := delay.GetFromQueue(ctx, rdb, "key")
        for res := range resCh {
            //延时打印数据,处理后续的逻辑;your own logic
            _ = res
            fmt.Println(res, time.Now())
        }
        //出错处理的逻辑
        for err := range errCh {
            if err != nil && err != context.Canceled && err != context.DeadlineExceeded {
                // your own logic
            }
        }
    }()

    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit
}

goper
413 声望25 粉丝

go 后端开发