如何实现python的mysql连接池并加入缓存过期
admin
2023-07-25 05:42:21
0次

mysql建立的连接,在8小时内都没有访问请求的话,mysql server将主动断开这条连接。在使用pymysql或MySQLdb操作数据库连接时,当cursor一直处于连接状态,未及时close时,连接池被占用。查看后台日志:

"MySQL server has gone away (%r)" % (e,))
pymysql.err.OperationalError: (2006, "MySQL server has gone away (TimeoutError(110, 'Connection timed out'))")

代码中未在query操作及时close cursor,在每个连接中,均要有cursor.close() 和 conn.close()操作。即:

def db_execute(query):
     conn = MySQLdb.connect(*)
     cur = conn.cursor()
     cur.execute(query)
     res = cur.fetchall()
     cur.close()
     conn.close()
     return res

这样的话会有性能问题,推荐使用SqlAlchemy.pool。那mysql中有办法实现吗?我们试试多线程和协程。

class MysqlConnect(object):
    """
    mysql connect 基类
    """

    def __init__(self, db_params=cmdb_test_params, maxconn=5):
        self.db_params = db_params
        self.maxconn = maxconn
        self.pool = Queue(maxconn)
        for i in range(maxconn):
            self.connect = self._connect()
            self.commit()
            self.cursor = self._cursor()

    def _connect(self):
        """
        mysql connect
        :return cursor:
        """
        key = ['host', 'port', 'user', 'password', 'database', 'charset']
        if not all([True if k in self.db_params else False for k in key]):
            raise Exception(list(self.db_params.keys()), "数据库连接失败,请检查配置参数")
        try:
            conn = pymysql.connect(**self.db_params)
            conn.autocommit(True)
            self.pool.put(self.connect)
        except pymysql.Error as e:
            logutil.Logger().error(e)
            traceback.print_exc()
            raise pymysql.Error("连接数据库失败 %s" % e)
        self.connect = conn
        return self.connect

    def _cursor(self):
        if self.connect:
            conn = self.pool.get()
            self.cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        else:
            self._connect()
            conn = self.pool.get()
            self.cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        return self.cursor

    def close(self):
        if self.connect:
            self.cursor.close()  # 关闭游标,未及时close时,连接池被占用 error code 2006
            self.pool.put(self.connect)
            self.connect = None

    def commit(self):
        try:
            if self.connect:
                self.connect.autocommit(True)
        except pymysql.Error as e:
            logutil.Logger().error(e)
            traceback.print_exc()
            raise pymysql.Error("数据库提交失败 %s" % e)
        finally:
            self.close()

    def rollback(self):
        try:
            if self.connect:
                self.connect.rollback()
        except pymysql.Error as e:
            logutil.Logger().error(e)
            traceback.print_exc()
            raise pymysql.Error("数据库回滚失败 %s" % e)
        finally:
            if self.connect:
                self.close()

    def __del__(self):
        self.commit()

    def query_execute(self, sql):
        try:
            if self.connect is None:
                self._connect()
                self._cursor()
            result_list = []
            self.cursor.execute(sql)
            for row in self.cursor.fetchall():
                result_list.append(list(row))
            return result_list
        except pymysql.Error as e:
            logutil.Logger().error(e)
            traceback.print_exc()
            raise pymysql.Error("数据库查询失败 %s" % e)
        finally:
            if self.connect:
                self.close()

    def dml_execute(self, sql):
        try:
            if self.connect is None:
                self._connect()
                self._cursor()
            if self.cursor is None:
                self._cursor()
            self.cursor.execute(sql)
            self.commit()
        except pymysql.Error as e:
            logutil.Logger().error(e)
            traceback.print_exc()
            self.rollback()
            raise pymysql.Error("数据库执行dml失败 %s" % e)
        finally:
            self.close()

    def dml_execute_many(self, sql):
        try:
            if self.connect is None:
                self._connect()
                self._cursor()
            if self.cursor is None:
                self._cursor()
            self.cursor.executemany(sql)
            self.commit()
        except pymysql.Error as e:
            logutil.Logger().error(e)
            traceback.print_exc()
            self.rollback()
            raise pymysql.Error("数据库执行dml失败 %s" % e)
        finally:
            self.close()

    def testmysqldb(self,ip,user,password,dbname,Strsql):
        try:
            self.connect = pymysql.connect(host=ip,user=user,passwd=password,charset='utf8')
            self.connect.select_db(dbname)
            self.query_execute(Strsql)
            return True
        except Exception as e:
            print(("Error %d :%s" %(e.args[0],e.args[1])))
            return False


相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...