需求是这样的:
用户每天最多领取礼包3次,每次insert一条记录,但是在并发的情况下会超出3次,如果解决?
有个已知的方法如下,但是并发下会产生死锁
INSERT INTO t_test (gift_id, user_id, `date`) SELECT v_gift_id, v_user_id, v_date FROM dual WHERE not exists (select * from t_test where `user_id` = v_user_id and `date` = v_date GROUP BY `user_id`, `date` HAVING count(*) > 2);
PHPz2017-04-18 09:09:46
As @junze said, it is usually made with redis
.
For example, store the number of times each user insert
in redis
中存储每个用户insert
的次数。假如key
格式是user:count
. If the key
format is user:count
Check firstcount
的值,小于3,执行插入,判断insert
的结果,insert成功的话,对key
user:count
执行incr
, incr user:count
,写入失败,不执行incr
every time.
This can avoid high concurrency exceeding 3.
At the same time, you can set this key
设置过期时间 expire user:count 60*60*24
to 1 day. After one day, the key will be deleted and re-initialized the next day.
PHPz2017-04-18 09:09:46
Use the string type of redis for counting. Redis supports high concurrency better
高洛峰2017-04-18 09:09:46
MySQL cannot help you do this. You can put the user's gift pack count in the cache, add some constants as the cache key based on the user's ID, store the count in it, and retrieve the count from the cache every time you insert. , judge whether it is less than your number of times, if it is less than your number, continue, if not, do not continue. If you continue, the number will be increased by one after insert and placed in the cache.
巴扎黑2017-04-18 09:09:46
Mysql doesn’t seem to have this mechanism. I feel that this control is also a logical control