In order to avoid repeated computations, the distributed lock service can be used in some time-consuming queries.
At the same time only one operation is in progress, the same kind of operation is waiting to retry.
The following code (FETCH_WITH_DIST_LOCK) defines a fetcher, a updater.
If Fetcher gets no data, it is updated with updater. After the update succeeds, the result is returned by Fetcher.
There are also cases where we want to update only one data, the update is multiple, but the update operation is not atomic.
We'll go through the update_with_dist_lock.
def fetch_with_dist_lock (Mc_store, Mutex_key, Fetcher, Updater, lock_time=3*60*1000, sleep_time=100 , retry_times=3): i = 0 while I < retry_times:i + = 1 need_update, results = fetcher () if NE Ed_update:if (Mc_store.add (Mutex_key, Lock_time)): Try:updater () Continue finally: #release the distribute mutex anyway Mc_sto Re.delete (Mutex_key) else:time.sleep ((sleep_time*1.0)/1000) Continue Retu RN Results #too much tries, but failed still. return Nonedef F_wrapper (f, *args, **kwargs): def _ (): Return F (*args, **kwargs) return _def update_with_dist _lock (Mc_store, Mutex_key, Updater, lock_time=60*1000, sleep_time=100, retry_times=5): i = 0 while I < Retry_time S:i + = 1 if (Mc_store.add (Mutex_key, Lock_time)): try: Updater () return True finally:mc_store.delete (mutex_key) Else: Time.sleep ((sleep_time*1.0)/1000) Continue return False