延迟队列-文章发布

2020-10-27  本文已影响0人  快感炮神
func listen(ctx context.Context) {
    for {
        now := strconv.Itoa(int(time.Now().Unix()))
        ids := []string{}
        if res, err := lib.Cache().ZRangeByScore(ctx, "news_pub", &redis.ZRangeBy{
            Min:    "-inf",
            Max:    now,
            Offset: 0,
            Count:  10,
        }).Result(); err == nil {
            ids = append(ids, res...)
        } else {
            fmt.Println(err.Error(), "a")
        }

        // 删除元素,避免重复获取
        if len(ids) != 0 {
            if err := lib.GetDB().Model(new(model.New)).Where("id in ("+strings.Join(ids, ",")+")").Update("status", 1).Error; err != nil {
                log.Fatal(err)
            } else {
                lib.Cache().ZRemRangeByScore(ctx, "news_pub", "-inf", now)
            }
        }

        time.Sleep(time.Second * 5)
    }
}

func main() {
    router := gin.Default()
    v1 := router.Group("v1")
    {
        v1.Handle(http.MethodPost, "/news", func(context *gin.Context) {
            _new := new(model.New)
            if err := context.ShouldBind(_new); err != nil {
                context.JSON(http.StatusBadRequest, gin.H{
                    "msg": "参数错误",
                })
            }

            // 如果时间比现在大,就把状态设为0(未发布)
            newstime, _ := time.ParseInLocation("2006-01-02 15:04:05", _new.Newstime, time.Local)
            if newstime.Unix() > time.Now().Unix() {
                _new.Status = 0
            } else {
                _new.Status = 1
            }

            // 入库
            if _, err := _new.Create(); err != nil {
                context.JSON(http.StatusOK, gin.H{
                    "msg": err.Error(),
                })
                return
            }

            context.JSON(http.StatusOK, gin.H{
                "msg":  "ok",
                "data": newstime.Unix(),
            })

            // 如果没有发布,则添加到 Sorted Set中
            if _new.Status == 0 {
                lib.Cache().ZAdd(context, "news_pub", &redis.Z{
                    Score:  float64(newstime.Unix()),
                    Member: _new.ID,
                })
            }
        })
    }

    // 监听队列
    go func(ctx context.Context) {
        listen(ctx)
    }(context.Background())

    router.Run()
}

上一篇下一篇

猜你喜欢

热点阅读