简体   繁体   English

如何进行数据完整性和错误处理?

[英]How to do data integrity and error handling?

Maybe this is a silly question, but after I asked some friends and googled for a while, and still cannot find a good explanation. 也许这是一个愚蠢的问题,但在我问了一些朋友并用Google搜索了一段时间之后,仍然找不到一个好的解释。

For example, I will do follow operations when one user posts: 例如,当一个用户发布时,我将执行以下操作:

  1. MySQL.insert(user, postTitle, postBody, time) MySQL.insert(用户,postTitle,postBody,时间)
  2. Redis.incr user.totalPostCount Redis.incr user.totalPostCount
  3. Redis.set last10Posts Redis.set last10Posts

So my question is, for example, if 1 success but 2 fails, what should I do? 所以我的问题是,例如,如果1成功但2失败,我该怎么办?

Ignore the redis error and continue? 忽略redis错误并继续? then user.totalPostCount is incorrect. 那么user.totalPostCount是不正确的。

Retry redis.incr ? 重试redis.incr What to do if retry fails? 如果重试失败该怎么办?

Return error to end-user says post fail and let user post again? 向最终用户返回错误说post fail并让用户再次发布?

Delete the post which previously inserted and return error to user? 删除先前插入的帖子并将错误返回给用户?

mysql.insert({user: user, postTitle: postTitle, postBody: postBody}, function(err, mysqlId) {
  if(err) { return Error(500); }
  redis.incr({user: user, totalPostCount}, function(err, result) {
    if(err) { mysql.delete(mysqlId)}
    setLast10Post({newPost: {postTitle...}}, function(err, result) {
      if(err) {mysql.delete(mysqlId); redis.decr({user.totalPostcount})}
    })
  })

}) })

You probably want those 3 operations to be a single atomic operation. 您可能希望这3个操作是单个原子操作。 That is, if any step fails, you want to make sure the whole thing fails and nothing happens. 也就是说,如果任何步骤失败,您需要确保整个过程失败并且没有任何反应。

So for scenario 1 (1 success, 2 fail), you'd rollback the SQL query and report an error. 因此,对于方案1(1个成功,2个失败),您将回滚SQL查询并报告错误。 You could forget anything happened or retry the whole process at that point. 您可以忘记发生的任何事情,或者在此时重试整个过程。

As for actually creating this transaction, perhaps this link is helpful. 至于实际创建此事务,也许这个链接很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM