duandazhen7306 2018-03-27 08:50
浏览 91
已采纳

在我可以使用query.Count()进行验证之前,Mongo编写了query.UpsertId多个文档

Description: I`m using mongoDB on my project. This is short logic for handler when user tries to put his item for sale. Before putting offer to mongo I validate the offer, so there would be no active offers with save assetId

Using:

  • mgo.v2

  • mongo 3.6

  • golang 1.10

Problem: If user clicks really fast sends several requests to my handler (lets say if he double click the mouse fast), validation doesn`t work as it seems like the first offer is not in the collection yet, so as a result I get 2-3 offers with same assetId.

I tried

  • Set mongoUrl?replicaSet=rs0, so our master and slaves would now about each other
  • Set time.Sleep(200 * time.Millisecond) after validation

Question:

Is there any way I can handle this with mongo instruments, or someone would suggest some other workaround?

Thank you in advance!

       count, _ := r.DB.C(sellOfferCollectionName).Find(
         bson.M{
            "state":     someState,
            "asset_id":  assetId,
            "seller_id": seller,
         },
       ).Count()

       if count > 0 {
           return 
       }       

       id := uuid.New().String()
            OfferModel := Offer{
                Id:           id,
                AssetId:      assetId,
                State:        someState,
                SellerId:     sellerId,
                CreatingDate: time.Now(),
            }
        if _, err := r.DB.C(sellOfferCollectionName).UpsertId(offer.Id, offer); err != nil {
            return err
        }

UPDATE

I tried to recreate the problem even more. So I wrote this little test code, so in result managed to write 60 documents before validation (count > 0) worked. This example fully recreates my problem.

type User struct {
  Id        string `bson:"_id"`
  FirstName string `bson:"first_name"`
  LastName  string `bson:"last_name"`
  State     bool   `bson:"state"`
}

func main() {
  mongoSession, mgErr := mgo.Dial("127.0.0.1:27018")

  if mgErr != nil {
    panic(mgErr)
  }

  var mongoDbSession = mongoSession.DB("test_db")

  for i := 0; i < 1000; i++ {
    go func() {
      count, _ := mongoDbSession.C("users").Find(
        bson.M{
          "state":      true,
          "first_name": "testUser",
        },
      ).Count()

      if count > 0 {
        return
      }

      user := User{
        Id:        uuid.New().String(),
        FirstName: "testUser",
        LastName:  "testLastName",
        State:     true,
      }

      if _, err := mongoDbSession.C("users").UpsertId(user.Id, user); err != nil {
        panic(mgErr)
      }
    }()
  }

  count, _ := mongoDbSession.C("users").Find(
    bson.M{
      "state":      true,
      "first_name": "testUser",
    },
  ).Count()

  fmt.Println(count)
  fmt.Scanln()
}
  • 写回答

2条回答 默认 最新

  • douhan6738 2018-03-29 14:28
    关注

    Eventually, after close investigation the bug, we found out that the reason was when user sent request it was handled in goroutine. Means a lot requests = a lot of concurrent goroutines. So, it out validator (check if the offer is in the collection), couldn't find it as it was not in the mongo yet. So, in the end, we decided to use redis as our validator.

    Here is short implementation:

    incr, err := redisClient.Incr(offer.AssetId).Result()
        if err != nil {
            return err
        }
    
        if incr > 1 {
            return errors.New("ASSET_ALREADY_ON_SALE")
        }
    
        redisClient.Expire(offer.AssetId, time.Second*10)
    

    Hope it will help someone facing same issue.

    Link on implementation description:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?