On the implementation of distributed Lock by redis

redis uses the setnx command to create locks. How long should I set the expiration time? How to set the failure time is too short, the method is not finished, the lock is automatically released, then concurrency problems will arise. If you set it for too long, other threads that acquire the lock may have to wait a little longer.
how to deal with this problem when only considering stand-alone redis?

Mar.23,2021

I wonder if it's too late for me to put out the fire.

do not use setnx to create an expired lock, use set key value nx ex time ( SET document address ) to create it. This ensures that setnx and expire combine into one atomic operation.

if the operation setnx then expire, is not atomic, it may cause new problems. For example, the program crashes abnormally after the setnx, causing the key to never expire, causing other threads requesting the lock to block all the time.

I hope it's not too late to put out the fire.


you can estimate the duration of your business request, usually between 50 and 100ms, and your expiration time can be set to 100ms. If you can set it to 1s higher, the next step in redis weight prevention is database weight prevention, which must be done, so even if the redis lock fails, the database will definitely be able to prevent it.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b370c9-2c06c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b370c9-2c06c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?