this reason fully illustrates the need for project-driven learning.
only if you know the specific project scenario can you decide what to do with the lock.
for example, if you can't get a resource, you have to wait, and if it's a synchronous request, you have to wait.
for example, if you can accept that if consistent, you can consider how long to wait for the lock, and then give up, logging or other compensation mechanisms.
of course this is similar to the difference between tryLock and tryLock (long timeout, TimeUnit unit) in ReentrantLock
depends on what kind of lock you want to implement, or based on what kind of usage scenario, for example, exclusive lock
, redis
cannot be implemented, and exclusive lock
blocks entry into the waiting queue if the lock is not acquired. Other processes will be notified to acquire locks when they release locks. redis
does not provide this notification mechanism based on key
, so he cannot implement exclusive locks
. However, the distributed exclusive lock
can be implemented by Zookeeper
.
another way to implement distributed locking is through optimistic locking and spin, which is the way you mentioned, but generally you will set the timeout, that is, redis
sets ttl
of key
. In this way, the process will not wait forever. This kind of lock is suitable for the situation where the operation time in the lock is relatively short and the lock competition is not so fierce.
in the case of 100 processes grabbing locks, in which the competition is so fierce, it is better to use exclusive locks.
requires a locked operation without such logic.
such as cached data updates.
1. The person who gets the lock checks the database and updates the data
2. Those who do not get the lock either return empty directly, or set the secondary cache to return the secondary cached data.
everyone has to get the same lock all the time. There should be no such operation, right?
it is necessary to have business logic to write code, otherwise it doesn't make sense
does the landlord have any new ideas now? I'm also curious. I feel like I've been querying redis to see if the lock has been deleted, and the performance is very low.
if err == nil && ok {
res, err := client.Get("num").Result()
fmt.Printf("num : %s\n", res)
num, err := strconv.Atoi(res)
err = client.Set("num", num+1, 0).Err()
_, err = client.Del("sync").Result()
if err != nil {
log.Println(err)
}
break
} else {
// if
if {
break
}
if {
break
}
if {
break
}
}
I don't know if this is possible