本文介绍了如何在 sequelize 中锁定表,等待另一个请求完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明:

我在数据库中有一张表,比如 Table1.只有一列AppNo(numeric),只有一行,当前值为0

I have one table in db say Table1. having only one column AppNo(numeric) and only single row, and current value is 0

我使用 Sequelize ORM 在 node.js 中创建了 API,名为 UpdateAppNo.

I have created API in node.js using Sequelize ORM named UpdateAppNo.

每当UpdateAppNo api 调用AppNo 的值应该增加1.

Whenever UpdateAppNo api called value of AppNo should increment by 1.

我想要的:

如果同时有 2 个或更多请求同时出现,当前请求应该等到前一个请求完成.

If 2 or more simultaneous request comes at a time, current request should wait until previous request to complete.

现在发生了什么:

如果前一个请求正在处理中,那么当前请求会抛出一个错误.

If previous request is in process, then current request throws an error.

推荐答案

这不是很好的文档或者很容易找到,但是你想要的是一个 Transaction 包装使用 lock 选项将其转换为 SELECT FOR UPDATE 语句.

This is not very well documented or easy to find, but what you want is a Transaction that wraps your find query which uses a lock option to turn it into a SELECT FOR UPDATE statement.

带有 lock 选项的查找查询将锁定行(您不需要锁定整个表)并且因为您正在使用事务,该操作将被提交或回滚取决于您的实例是否持有锁.

The find query with the lock option will lock the row (you don't need to lock the entire table) and because you are using a transaction, the action will either be committed or rolled back depending on whether or not your instance holds the lock.

您需要修改 这些示例供您使用.

You will want to adapt the code found in these examples for your use.

这篇关于如何在 sequelize 中锁定表,等待另一个请求完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 21:16