简体   繁体   English

如何防止在处理行时选择该行?

[英]How to prevent selection of the row while it is being handled?

I have MySQL (InnoDB) table with the column is_locked which shows current state of the record (is it being handled by system now, or not). 我有带有列is_locked MySQL(InnoDB)表,该表显示记录的当前状态(现在是由系统处理还是不由系统处理)。

On the other hand, I have many nodes that perform SELECT * FROM table_name WHERE is_locked = 0 and then handles got rows from this table. 另一方面,我有许多执行SELECT * FROM table_name WHERE is_locked = 0节点,然后处理从该表获得的行。

In my code I do this: 在我的代码中,我这样做:

  1. System takes the row from DB ( SELECT * FROM table_name WHERE is_locked = 0 ) 系统从数据库获取行( SELECT * FROM table_name WHERE is_locked = 0
  2. System lockes the row by command UPDATE table_name SET is_locked = 1 WHERE id = <id> 系统通过命令UPDATE table_name SET is_locked = 1 WHERE id = <id>锁定行

Problem: Nodes are working very fast, all of them may get the same row, before first of them will update the row and set is_locked to 1 问题:节点运行非常快,所有节点都可能获得同一行,然后它们首先更新该行并将is_locked设置为1

I found out LOCKING of the tables, but I don't think it is the right way. 我发现了表的锁定,但我认为这不是正确的方法。 Can anybody tell me, how to handle such cases? 谁能告诉我如何处理这种情况?

I recommend two things: 我建议两件事:

  • Limit your select to one, as you're dealing with concurrency issues, it is better to take smaller "bites" with each iteration 将选择范围限制为一个,因为您要处理并发问题,因此每次迭代最好取较小的“位数”

  • Use transactions, this allows you to start the transaction, get the record, lock it and then commit the transaction. 使用事务,这使您可以启动事务,获取记录,将其锁定然后提交事务。 This will force mysql to enforce your concurrency locks. 这将迫使mysql强制执行您的并发锁。

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

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