It mainly introduces the ordered collection of python operations redis, and the use of redis to implement distributed locks.
An ordered set is a data type, similar to a mixture between a set and a hash. Like a set, a sorted set consists of unique, non-repeating string elements, so in a sense, an ordered set is also a set. However, although the elements in the set are not sorted, each element in the sorted set is associated with a floating point value called a score (which is why this type is also similar to a hash, because each element Are all mapped to a value). In addition, the elements in an ordered set are in order (therefore, they are not sorted on request, and the order is used to indicate the particularity of the data structure of the sorted set)
import redis
r = redis.Redis(**config.REDIS_CONF)
One or more members added to the ordered set, or updated score, if it already exists
redis.zadd('my-key','name1',1.1,'name2',2.2, name3=3.3,name4=4.4)
Returns the members in the specified score range in the ordered set, sorted from low to high score.
r.zrangebyscore(name, min, max, start=None, num=None,withscores=False, score_cast_func=float)
If '' start '' and 'num' 'are specified, a sliced range is returned.
'' withscores '' means return scores and values. The return type is a list of (value, score) pairs
'score_cast_func''A callable function used to convert the score return value
Return the value range between the sorted set '' name '' '' start '' and '' end '' in ascending order.
zrange(self, name, start, end, desc=False, withscores=False,score_cast_func=float):
'start' 'and' 'end' 'are arranged in ascending order.
start
and end
can be negative, indicating the end of the range.
'' desc ''A Boolean value indicating whether to sort the results downward
'' withscores '' means return scores and values.
The return type is a list of (value, score) pairs
'' score_cast_func ''A callable function used to convert the score return value
I wrote distributed lock code. If there are multiple machines deploying scripts, only one machine will run the script at the same time. Made a decorator for the lock function.
def check_lock(func_or_cls):"""
redis distributed lock
: param func_or_cls::return:"""
def wapper(self,*args,**kwargs):
job_lock = r.set(self.lock_name,1, ex=60, nx=True)if job_lock is True:try:
res =func_or_cls(self,*args,**kwargs)
except Exception:
res = None
r.delete(self.lock_name)return res
else:
pass
return wapper
Examples of usage:
classMqMessageHandler(object):"""Operation corresponding to each topic"""
@ staticmethod
def topic_call_back(msg):"""
Operations after subscribing to topic
: param msg::return:"""
Loggers(log_name='MqMessageHandler')
flag, text_json =bytes_to_dict(msg.body) #Convert bytes type to dictionary type
logging.info({"msg_id": msg.id,"msg_body": msg.body,"text_json": text_json})
now_date = Utils.get_date_str().replace("-","") #Get today's date
now_time = Utils.timestamp_second()if msg.body == b'OK':
refresh_key = f"media_auth_refresh_{now_date}"
r.zadd(refresh_key, now_time,0) #Join the ordered set of key current time score (0 means a new action is required)
elif flag:
new_key = f"media_auth_new_{now_date}"
r.zadd(new_key, text_json,0)else:
logging.error({"msg_id": msg.id,"msg_body": msg.body})
The lock is mainly realized by the set method. The detailed description of the set method is as follows:
def set(self, name, value, ex=None, px=None, nx=False, xx=False):"""
Set the value at key ``name`` to ``value````ex`` sets an expire flag on key ``name``for``ex`` seconds.``px`` sets an expire flag on key ``name``for``px`` milliseconds.``nx``ifset to True,set the value at key ``name`` to ``value`` only
if it does not exist.``xx``ifset to True,set the value at key ``name`` to ``value`` only
if it already exists."""
Is based on the characteristics of the parameter nx, if you set nx=True ,Only when the value corresponding to this name does not exist will it return True.
Recommended Posts