Description
Yesterday afternoon colleagues reflect the operation and maintenance platform Authority plus go, but actually did not take effect, at that time briefly looked at the database is in effect, but Redis is not synchronized, permissions to add to MySQL and then will brush a redis. Did not brush success, at that time because in busy ansible API some things, did not hurry to get.
Finding the problem actually calling the class
class Permission(DbBase): ‘‘‘权限认证类操作‘‘‘ def __init__(self): """权限认证类 :rtype: object """ super(Permission, self).__init__() self.SESSION_NAME = conf.SESSION_NAME .....
Parent class Dbbase
It is important to note that this does not take the inheritance method, but will be initialized each time, when the thought is to inherit two classes, so in the actual way to write, this first regardless. If you have any questions, change them later.
class DbBase(object): ‘‘‘数据库基类操作‘‘‘ def __init__(self): self.mysql = db.Mysql() # instance mysql object self.redis = db.Redis() # instance redis object ‘‘‘Call Mysql Object methods‘‘‘ self._db_write = self.mysql.write self._db_fetchone = self.mysql.fetchone self._db_fetchall = self.mysql.fetchall ‘‘‘Redis Users Session key‘‘‘ self.session_key = "----"
Base class
class Redis(): def __init__(self): parmas = { ‘host‘ : conf.REDIS_HOST, ‘port‘ : conf.REDIS_PORT, ‘password‘ : conf.REDIS_PASS, } # 改一下方法, ttl一直获取为-2 self.cursor = redis.Redis(**parmas)
View Code 1
class Redis(StrictRedis): """ Provides backwards compatibility with older versions of redis-py that changed arguments to some commands to be more Pythonic, sane, or by accident. """
2
See the long connection parameter socket_keepalive to see the code.
class StrictRedis(object): def __init__(self, host=‘localhost‘, port=6379, db=0, password=None, socket_timeout=None, socket_connect_timeout=None, socket_keepalive=None, socket_keepalive_options=None, connection_pool=None, unix_socket_path=None, encoding=‘utf-8‘, encoding_errors=‘strict‘, charset=None, errors=None, decode_responses=False, retry_on_timeout=False, ssl=False, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None, ssl_ca_certs=None, max_connections=None):
3
Finally, navigate to this method, the default is to go to the short link
# TCP_KEEPALIVE if self.socket_keepalive: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) for k, v in iteritems(self.socket_keepalive_options): sock.setsockopt(socket.SOL_TCP, k, v)
Problem speculation
There may be a problem with long-term links, and then the link fails and then the call goes wrong.
Code modification
Code has comments
‘‘‘Redis DB Object‘‘‘class Redis(): def __init__(self): # 这里的 socket_keepalive是为长链接,因为后面会很多 # 子类继承这个类,为保持连接的长久性 parmas = { ‘host‘ : conf.REDIS_HOST, ‘port‘ : conf.REDIS_PORT, ‘password‘ : conf.REDIS_PASS, ‘socket_keepalive‘ : True, } # 改一下方法, ttl一直获取为-2 self.cursor = redis.Redis(**parmas)
Wait for observation
Reminder: Things that involve databases must pay attention to long and short link problems