触发器是异步的吗?
我有一个表 A,它维护表 B 中的总用户数。我所关心的是表 A 中的计数与表 B 中的用户数同步。
因此,每当我在表 B 中插入用户时,我都会希望计数根据用户的插入或删除而增加/减少。
有两种方法:- a) 如果我在表 B 中插入行,我可以在一个存储过程中发出表 A 的更新计数。这导致两个命令插入然后更新。因此说需要 2 秒。 (假设每个 txn 在 1 秒内)
b)我可以在存储过程中编写插入命令。另外,定义一个触发器,用于在表 A 中的插入完成后更新表 A 中的计数。对我来说,这只需要 1 秒的时间,即在表 B 中插入行。我认为更新表 B 中计数的“插入后触发器”发生在后台,因此是异步或非同步的。阻塞。
这个假设是否正确,或者这两种方法将花费相同的时间。
注意:我不关心表 A 中更新计数的时间。因此,我正在寻找一种以非阻塞模式(如队列)执行同步作业的方法!
有什么建议/意见吗?
I have a table A which maintains count of total users in Table B. All I care is that the count in Table A is in sync with the number of users in the table B.
So, whenever I insert a user in Table B, I want the count to be incremented/decremented depending on insert of user or delete.
There are two ways:-
a) In case I am inserting the row in Table B, I can issue the update count on Table A in one stored procedure. This result in two commands insert followed by update. Hence say take 2 secs. ( assuming each txn in 1 sec)
b) I can write the insert command in the stored procedure. Also, define a trigger which updates the count in table A after the insert in Table A is completed. To me this will only take time of 1 sec which is just inserting the row in Table B. I presume that the 'after insert trigger' which updates the count in Table B happens in the background and hence is asynchronous or non-blocking.
Is this presumption correct or shall both the approaches will take equal time.
Note: I don't care the timing of update counts in table A. Hence I am looking for a way which does the sync job in non-blocking mode like in a queue!
ANy suggestions/comments?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,触发器以与存储过程相同的方式绝对同步执行。这意味着,如果您开始执行诸如更新触发器中的计数之类的操作,则可以使使用自动提交执行的简单查询在事务中执行大量工作,因此很可能会出现死锁。你应该意识到这一点。
如果您不希望它同步,我想您可以让它插入待处理更改的表中,然后使用异步过程来更新它。从长远来看,这可能会避免很多死锁(据我所知,插入到没有二级索引的表中不能与另一个插入到同一个表中发生死锁)
No, triggers are executed absolutely synchronously in the same way a stored procedure would be. This means that if you start doing things like updating counts in triggers, you can make a simple query executed with autocommit do a lot of work in a transaction hence be very likely to deadlock. You should be aware of this.
If you don't want it synchronous, I suppose you could make it do an insert into a table of pending changes, then have an asynchronous process which updates it. This would probably avoid a lot of deadlocks in the long run (inserting into a table with no secondary indexes cannot deadlock with another insert into the same table, AFAIK)