zoukankan      html  css  js  c++  java
  • Mysql 连接池

    通常,如果我们的服务涉及到mysql的操作,当一个新的请求进来的时候,可以先连接mysql, 使用完之后再断开连接即可。



    但这样做有个弊端,当请求量巨大时,会在瞬间有大量的数据库连接与断开操作,这是非常影响 mysql 性能的做法。此时,我们就需要使用Mysql连接池。

    在 Python 服务中使用 Mysql 连接池

    1、建立连接池,sqllib.py

    import pymysql
    from DBUtils.PooledDB import PooledDB
    
    import Config
    
    class MysqlPool():
        __pool = None
        def __init__(self):
            self.conns = self.getPools()
    
        def getPools(self):
            __pool = PooledDB(
                creator=pymysql,
                mincached=1,
                maxcached=20,
                host=Config.host,
                user=Config.user,
                passwd=Config.password,
                db=Config.dbname,
                port=Config.port,
                charset=Config.charset
            )
            return __pool
            
    
    • mincached: 最小空闲连接数
    • maxcached: 最大空闲连接数
    • maxconnections: 最大允许连接数


    2、使用连接池,server.py

    from sqllib import MysqlPool
    
    pool = MysqlPool()
    
    @app.route('/test', method=['POST'])
    def test():
        db = pool.conns.connection()
        processing()
        db.close()
    
    • db = pool.conns.connection()

      从连接池中获取一个连接
    • db.close()

      连接使用完毕,将连接放回连接池。
  • 相关阅读:
    SpringMvc
    Spring-Aop
    Spring-IOC
    Spring模块划分
    队列
    稀疏数组
    数据结构
    Nginx配置实例
    Nginx常用命令
    视频断点播放:h5+jquery
  • 原文地址:https://www.cnblogs.com/Fosen/p/12609070.html
Copyright © 2011-2022 走看看