I don’t quite understand the meaning of your code, and it doesn’t seem to match your description.
It is not impossible to use redis, but the efficiency may be a bit low. It is recommended to use optimistic locking to solve this problem.
For example: Suppose there is a version field in the order table. This field can only be incremented in one direction (usually +1). When selecting, check version as well:
SELECT ..., version FROM order
WHERE ...;
UPDATE order
SET ...,
version = version+1
WHERE version = 上一个SELECT语句带出来的version值
Suppose that User A and User B find orders with order_id=1, version=1 within a certain period of time, one after another or at the same time. Due to the existence of mysql row lock during UPDATE, only one user will UPDATE successfully (1 rows affected). Another user's UPDATE failed (0 rows affected), and then you can judge whether the user successfully grabbed the order based on the number of rows returned after the UPDATE.
I don’t quite understand the meaning of your code, and it doesn’t seem to match your description.
It is not impossible to use redis, but the efficiency may be a bit low. It is recommended to use optimistic locking to solve this problem.
For example:
Suppose there is a version field in the order table. This field can only be incremented in one direction (usually +1). When selecting, check
version
as well:Suppose that User A and User B find orders with order_id=1, version=1 within a certain period of time, one after another or at the same time. Due to the existence of mysql row lock during UPDATE, only one user will UPDATE successfully (1 rows affected). Another user's UPDATE failed (0 rows affected), and then you can judge whether the user successfully grabbed the order based on the number of rows returned after the UPDATE.