mongodb - Mongodb异常恢复保存的事务

标签 mongodb grails transactions

每当不同的用户同时下订单和更新相同的菜单时,我的grails应用程序中都会出现starnge场景,它会抛出乐观的锁定异常,现在就像这样

 def orderApi {
          // credits are deducted before try catch
           // code
          // .....
  try {
        // code to place order
}
catch(Exception e){
    // send mail for exception
    orderFailed = true
}

if(orderFailed){
    refundUserCredits(order)
}
}


 def refunduserCredits(Order order){
      User user = order.user
      user.credits = order.credits
      if(!user.save()){
         println "Unable to save user"  // but it does not save the credits 

             }
}

我想因为我发现了异常,并退还了积分并保存了应该保存的用户对象。同样奇怪的是,如果不保存用户信用,它应该进入!user.save()并打印消息,但它甚至没有这样做。

最佳答案

我认为使用transaction将使您受益。它使您可以将订单下达和信用扣除作为一个全有或全无的单元 bundle 在一起。现在,您正在实施自己的事务管理。它会像这样...

Order.withTransaction { status ->
    // deduce credits and attempt to place order. save() all you want.

    if(orderFailed) status.setRollbackOnly()
}

因此,只有一切顺利,订单和用户更改才会保留。

关于mongodb - Mongodb异常恢复保存的事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35405756/

相关文章:

mongodb - 从 mongo 集合中的数组中删除条目

javascript - MongoDB,如果新值不为空,则更新集合字段

grails - 如何使用内置的Grails/GORM方法表示此查询

java - 使用可序列化隔离的同一事务的 2 个实例出现死锁

php - 更多查询中的 MySQL 事务

javascript - 无法返回值(我认为范围问题)

mysql - 如何在laravel项目中使用多个数据库连接?

grails - 在 Grails 中用自己的方法扩展 SpEL?

Grails:为什么来自 GET 请求的 JSON 没有绑定(bind)到 Controller 操作中的命令对象?

java - Spring - @Transactional 不启动事务