美文网首页
延迟队列-文章发布

延迟队列-文章发布

作者: 快感炮神 | 来源:发表于2020-10-27 14:51 被阅读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()
    }
    
    

    相关文章

      网友评论

          本文标题:延迟队列-文章发布

          本文链接:https://www.haomeiwen.com/subject/ghlxvktx.html