universal-object-pool


Nameuniversal-object-pool JSON
Version 1.2 PyPI version JSON
download
home_page
Summarycommmon universal_object_pool
upload_time2023-10-26 09:19:52
maintainerydf
docs_urlNone
authorbfzs
requires_python
licenseBSD License
keywords commmon universal_object_pool
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ## pip install universal_object_pool

此包能够将一切任意类型的python对象池化,是万能池,适用范围远大于单一用途的mysql连接池 http连接池等。

使用这个通用对象池框架,自带实现了4个对象池例子。可以直接开箱用这四个对象池,也可以作为例子学习对象池用法。

contrib 文件夹自带演示了4个封装,包括http pymsql webdriver paramiko(操作linux的python包)的池化。

<pre style="color: darkgreen;font-size: medium">
python 通用对象池,socket连接池、mysql连接池归根结底都是对象池。
mysql连接池就是pymsql.Connection类型的对象池,一切皆对象。
只是那些很常用的功能的包都有相关的池库,池都是为他们特定的功能定制服务的,不够通用。

编码中很多创建代价大的对象(耗时耗cpu),但是他们的核心操作方法只能是被一个线程占用。

例如mysql,你用同一个conn在不同线程同时去高并发去执行插入修改删除操作就会报错,而且就算包不自带报错,
带事务的即使不报错在多线程也容易混乱,例如线程1要吧conn roallback,线程2要commit,conn中的事务到底听谁的?
例如一个浏览器要并发打开多个网页,线程1命令浏览器打开新浪,线程2命令浏览器打开搜狐,那么浏览器到底听谁的?
一个http链接要打开百度新闻的第一页,另外一个线程又让他打开百度新闻的第二页,那么这个socket到底听谁的?
解决类似这种抓狂的场景,如果不想再函数内部频繁创建和摧毁,那么就要使用池化思想。


如果一个对象的创建代价大例如耗时耗费代码行数长(耗cpu),并且他的核心操作方法是耗时的并且是多线程不安全的,
那么就有必要使用池化,使程序运行速度加快。和这个对象代表的是不是一个socket连接,是不是一个浏览器,没有任何关系。




</pre>



[这是一篇很好的博客,说明连接池重要性: ](https://blog.csdn.net/claroja/article/details/103204159?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166364368816782388023926%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=166364368816782388023926&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-2-103204159-null-null.nonecase&utm_term=python%20%20DBUtils&spm=1018.2226.3001.4450)



```




编码中有时候需要使用一种创建代价很大的对象,而且这个对象不能被多线程同时调用他的操作方法,

比如mysql连接池,socket连接池。
很多这样的例子例典型如mysql的插入,如果多线程高并发同时操作同一个全局connection去插入,很快就会报错了。
那么你可能会为了解决这个问题的方式有如下:

1.你可能这么想,操作mysql的那个函数里面每一次都临时创建mysql连接,函数的末尾关闭coonection,
  这样频繁创建和摧毁连接,无论是服务端还是客户端开销cpu和io高出很多。

2.或者不使用方案1,你是多线程的函数里面用一个全局connection,但是每一个操作mysql的地方都加一个线程锁,
  使得不可能线程1和线程2同时去操作这个connction执行插入,如果假设插入耗时1秒,那么100线程插入1000次要1000秒。

正确的做法是使用mysql连接池库。如果设置开启的连接池中的数量是大于100,100线程插入1000次只需要10秒,节省时间100倍。
mysql连接池已经有知名的连接池包了。如果没有大佬给我们开发mysql连接池库或者一个小众的需求还没有大神针对这个耗时对象开发连接池。
那么可以使用 ObjectPool 实现对象池,连接池就是对象池的一种子集,connection就是pymysql.Connection类型的对象,连接也是对象。
这是万能对象池,所以可以实现webdriver浏览器池。对象并不是需要严格实实在在的外部cocket或者浏览器什么的,也可以是python语言的一个普通对象。
只要这个对象创建代价大,并且它的核心方法是非线程安全的,就很适合使用对象池来使用它。




```

## 1.常问问题回答

### 1.1 对象池是线程安全的吗?

```
这个问题牛头不对马嘴 ,对象池就是为多线程或者并发而生的。
你想一下,如果你的操作只有一个主线程,那直接用一个对象一直用就是了,反正不会遇到多线程要使用同一个对象。

你花脑袋想想,如果你的代码是主线程单线程的,你有必要用dbutils来搞mysql连接池吗。
直接用pymysql的conn不是更简单更香吗。
web后端是uwsgi gunicorn来自动开多线程或者协程是自动并发的,虽然你没亲自开多线程,但也是多线程的,需要使用连接池。

任何叫池的东西都是为并发而生的,如果不能多线程安全,那存在的意义目的何在?

```

### 1.2 对象池 连接池 线程池有什么区别。

```
连接池就是对象池,连接池一般是链接数据库 或者中间件或者socket的对象,比如mysql的connection,有的对象并不是链接什么socket,
但是创建代价大,方法非线程安全,就是对象池。连接池是对象池的一个子集。

线程池和对象池关系很小,此对象池可以实现了一切对象池化,但并不能拿来实现线程池。
如果要看线程池,https://github.com/ydf0509/threadpool_executor_shrink_able 此项目实现了线程池。


https://blog.csdn.net/Alan_Mathison_Turing/article/details/78512410 这个讲得对象池和线程池区别,讲的不错。

一个对象池的基本行为包括:

创建对象newObject()
借取对象getObject()
归还对象freeObject()

线程池
首先摆出结论:线程池糅合了对象池模型,但是核心原理是生产者-消费者模型。

线程池并不是像多线程把某个线程借出去使用然后利用完了归还,线程池里面的线程都是while true的死循环,
不会像对象池例如mysql的conn查询一下几十毫秒钟就用完了,线程池里面的线程对象是永不结束的,没有借出去使用用完了后归还这种事情。

所以不能想着学习池化mysql connection或者selnium的driver,也把threading.Thread池化呢,Thread对象随着run方法的结束就会自动摧毁了
,无法人为的使Thread不摧毁,也就是说线程是随着run方法运行完成就自动结束了不可放到池子里面反复拿出来短暂利用,那么线程池是如何复用线程的呢?
因为上面说了线程随着run方法运行完成就自动结束了是一次性的,那么主要是就是把线程池的每个线程的run方法设计成无限蒙蔽死循环的while 1永不结束就能解决复用问题了,
每个线程的run方法都是在while 1 里面 fun,args = queue.get(block=True),每取出一个任务后就在当前线程执行 fun(*agrs),所以线程一直是那个线程,
但是可以运行的函数和函数参数却是无限可能的。
任何线程池实现都是有个queue,生产者往queue里面submit任务,
消费者是例如100个线程,每个线程里面跑的函数都是while True的死循环函数,while 1里面不断的用queue.get从queue里面拉取任务,
拉取一个任务,就立即fun(x,y)这么去运行。任何语言任何人实现线程池一定是这个思路这么写的,没有例外。

说到死循环那就很有趣了,这里是线程池设计的一个难点重点,如果while True死循环,那线程池不是无敌了无解了,代码那不是永远结束不了?
线程池里面设计的一个难点就包括这里,所以很多人写的线程池都很难用,要么程序永不结束,要么设计成了线程池的queue里面还有任务没完成,
程序就结束了,所以pool.submit,很多人搞的线程池在代码最结尾要加上pool.termit什么玩意的,可以百度博客园python线程池好多就是这样的,
没有几个人设计的手写线程池达到了 concurrent.futures.Threadpoolexecutor那么好用的程度,最主要是不了解守护线程,
很多人都是搞的非守护线程,导致发明的线程池比内置的concurrent.futures.Threadpoolexecutor好用程度差十万八千里。
如果把while 1死循环的线程设置为守护线程,那么当主线程结束后,守护线程就会自动随程序结束了。当然了光设置守护线程还不够,
如果主线程把任务都submit到queue里面了,实际上线程池应该还需要运行queue里面的任务,所以还需要加个判断,要加上 atexit.register的钩子,
让任务执行完成才关闭。设计一个好用的线程池还是很难的,设计一个死循环导致代码永不能自动结束的线程池就简单很多了。
比如这个线程池  https://github.com/mingxiaoHe/ThreadPool/blob/master/threadpool.py 设计得很悲催,
必须手动在整个项目最末未加上 pool.close(),而且不能加在代码中间,因为加载中间会导致如果之后继续提交任务就没线程能力执行了,太难了用了这种
主要是不知道守护线程用途。

还有这个 https://github.com/shengqi158/ThreadPool/blob/master/ThreadPool.py,最末未要加上threadpool.task_join(),
很多封装的需要最最末尾加一句,主要是不知道守护线程用途。


线程池的思路于对象池几乎完全不同。



```

## 2.利用对象池来封装任意类型的池演示

contrib 文件夹自带演示了4个封装,包括http pymsql webdriver paramiko(操作linux的python包)的池化。

### 2.0 例如使用万能对象池包实现的 nb_http_client

[nb_http_client](https://github.com/ydf0509/nb_http_client)

nb_http_client 是 python 史上性能最强的http客户端,比任意自带和三方请求包快很多倍。

### 2.1 mysql 池化

以下是pymysql_pool的池化代码,使用has a模式封装的PyMysqlOperator对象,你也可以使用is a来继承方式来写,但要实现clean_up等方法。

```python
import copy

import pymysql
import typing
from universal_object_pool import ObjectPool, AbstractObject
from threadpool_executor_shrink_able import BoundedThreadPoolExecutor
import threading
import time
import decorator_libs

"""
这个是真正的用pymsql实现连接池的例子,完全没有依赖dbutils包实现的连接池。
比dbutils嗨好用,实际使用时候不需要操作cursor的建立和关闭。

dbutils官方用法是

pool= PooledDB()
db = pool.connection()
cur = db.cursor()
cur.execute(...)
res = cur.fetchone()
cur.close()  # or del cur
db.close()  # or del db

"""


class PyMysqlOperator(AbstractObject):
    error_type_list_set_not_available = []  # 出了特定类型的错误,可以设置对象已经无效不可用了,不归还到队列里面。

    # error_type_list_set_not_available = [pymysql.err.InterfaceError]

    def __init__(self, host='192.168.6.130', user='root', password='123456', cursorclass=pymysql.cursors.DictCursor,
                 autocommit=False, **pymysql_connection_kwargs):
        in_params = copy.copy(locals())
        in_params.update(pymysql_connection_kwargs)
        in_params.pop('self')
        in_params.pop('pymysql_connection_kwargs')
        self.conn = pymysql.Connection(**in_params)

    """ 下面3个是重写的方法"""

    def clean_up(self):  # 如果一个对象最近30分钟内没被使用,那么对象池会自动将对象摧毁并从池中删除,会自动调用对象的clean_up方法。
        self.conn.close()

    def before_use(self):
        self.cursor = self.conn.cursor()
        self.core_obj = self.cursor  # 这个是为了operator对象自动拥有cursor对象的所有方法。

    def before_back_to_queue(self, exc_type, exc_val, exc_tb):
        if exc_type:
            self.conn.rollback()
        else:
            self.conn.commit()
        self.cursor.close()  # 也可以不要,因为每次的cusor都是不一样的。

    """以下可以自定义其他方法。
    因为设置了self.core_obj = self.cursor ,父类重写了__getattr__,所以此对象自动拥有cursor对象的所有方法,如果是同名同意义的方法不需要一个个重写。
    """

    def execute(self, query, args):
        """
        这个execute由于方法名和入参和逻辑与官方一模一样,可以不需要,因为设置了core_obj后,operator对象自动拥有cursor对象的所有方法,可以把这个方法注释了然后测试运行不受影响。
        :param query:
        :param args:
        :return:
        """
        return self.cursor.execute(query, args)


if __name__ == '__main__':
    mysql_pool = ObjectPool(object_type=PyMysqlOperator, object_pool_size=100, object_init_kwargs={'port': 3306})


    def test_update(i):
        sql = f'''
            INSERT INTO db1.table1(uname ,age)
        VALUES(
            %s ,
            %s)
        ON DUPLICATE KEY UPDATE
            uname = values(uname),
            age = if(values(age)>age,values(age),age);
        '''
        with mysql_pool.get(
                timeout=2) as operator:  # type: typing.Union[PyMysqlOperator,pymysql.cursors.DictCursor] #利于补全
            print(id(operator.cursor), id(operator.conn))
            operator.execute(sql, args=(f'name_{i}', i * 4))
            print(
                operator.lastrowid)  # opererator 自动拥有 operator.cursor 的所有方法和属性。 opererator.methodxxx 会自动调用 opererator.cursor.methodxxx


    operator_global = PyMysqlOperator()


    def test_update_multi_threads_use_one_conn(i):
        """
        这个是个错误的例子,多线程运行此函数会疯狂报错,单线程不报错
        这个如果运行在多线程同时操作同一个conn,就会疯狂报错。所以要么狠low的使用临时频繁在函数内部每次创建和摧毁mysql连接,要么使用连接池。
        :param i:
        :return:
        """
        sql = f'''
            INSERT INTO db1.table1(uname ,age)
        VALUES(
            %s ,
            %s)
        ON DUPLICATE KEY UPDATE
            uname = values(uname),
            age = if(values(age)>age,values(age),age);
        '''

        operator_global.before_use()
        print(id(operator_global.cursor), id(operator_global.conn))
        operator_global.execute(sql, args=(f'name_{i}', i * 3))
        operator_global.cursor.close()
        operator_global.conn.commit()


    thread_pool = BoundedThreadPoolExecutor(20)
    with decorator_libs.TimerContextManager():
        for x in range(200000, 300000):
            thread_pool.submit(test_update, x)
            # thread_pool.submit(test_update_multi_threads_use_one_conn, x)
        thread_pool.shutdown()
    time.sleep(10000)  # 这个可以测试验证,此对象池会自动摧毁连接如果闲置时间太长,会自动摧毁对象


``` 

### 2.2 linux 操作神库 paramiko 的池化,例如可以大幅度加快文件传输和大幅度加快有io的命令。

比如有很多几kb的小文件需要上传,对象池 + 线程池可以大幅度提升上传速度

比如让linux执行有io耗时的curl命令,对象池 + 线程池可以大幅度提升命令执行效率。

所以此对象池可以池化一切python对象,不仅是是数据库连接。

```python
import time

import decorator_libs
import paramiko
import nb_log
from threadpool_executor_shrink_able import BoundedThreadPoolExecutor

from universal_object_pool import AbstractObject, ObjectPool

"""
 t = paramiko.Transport((self._host, self._port))
        t.connect(username=self._username, password=self._password)
        self.sftp = paramiko.SFTPClient.from_transport(t)

        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self._host, port=self._port, username=self._username, password=self._password, compress=True)
        self.ssh = ssh
"""


class ParamikoOperator(nb_log.LoggerMixin, nb_log.LoggerLevelSetterMixin, AbstractObject):
    """
    这个是linux操作包的池化。例如执行的shell命令耗时比较长,如果不采用池,那么一个接一个的命令执行将会很耗时。
    如果每次临时创建和摧毁linux连接,会很多耗时和耗cpu开销。
    """
    def __init__(self, host, port, username, password):
        # self.logger = nb_log.get_logger('ParamikoOperator')

        t = paramiko.Transport((host, port))
        t.connect(username=username, password=password)
        self.sftp = paramiko.SFTPClient.from_transport(t)

        ssh = paramiko.SSHClient()
        # ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, port=port, username=username, password=password, compress=True)  # 密码方式

        # private = paramiko.RSAKey.from_private_key_file('C:/Users/Administrator/.ssh/id_rsa')  # 秘钥方式
        # ssh.connect(host, port=port, username=username, pkey=private)
        self.ssh = self.core_obj = ssh

        self.ssh_session = self.ssh.get_transport().open_session()

    def clean_up(self):
        self.sftp.close()
        self.ssh.close()

    def before_back_to_queue(self, exc_type, exc_val, exc_tb):
        pass

    def exec_cmd(self, cmd):
        # paramiko.channel.ChannelFile.readlines()
        self.logger.debug('要执行的命令是: ' + cmd)
        stdin, stdout, stderr = self.ssh.exec_command(cmd)
        stdout_str = stdout.read().decode()
        stderr_str = stderr.read().decode()
        if stdout_str != '':
            self.logger.info('执行 {} 命令的stdout是 -- > \n{}'.format(cmd, stdout_str))
        if stderr_str != '':
            self.logger.error('执行 {} 命令的stderr是 -- > \n{}'.format(cmd, stderr_str))
        return stdout_str, stderr_str


if __name__ == '__main__':
    paramiko_pool = ObjectPool(object_type=ParamikoOperator,
                               object_init_kwargs=dict(host='192.168.6.130', port=22, username='ydf',
                                                       password='372148', ),
                               max_idle_seconds=120, object_pool_size=20)

    ParamikoOperator(**dict(host='192.168.6.130', port=22, username='ydf', password='372148', ))


    def test_paramiko(cmd):
        with paramiko_pool.get() as paramiko_operator:  # type:ParamikoOperator
            # pass
            ret = paramiko_operator.exec_cmd(cmd)
            print(ret[0])
            print(ret[1])


    thread_pool = BoundedThreadPoolExecutor(20)
    with decorator_libs.TimerContextManager():
        for x in range(20, 100):
            thread_pool.submit(test_paramiko, 'date;sleep 20s;date')  # 这个命令单线程for循环顺序执行每次需要20秒,如果不用对象池执行80次要1600秒
            # thread_pool.submit(test_update_multi_threads_use_one_conn, x)
        thread_pool.shutdown()
    time.sleep(10000)  # 这个可以测试验证,此对象池会自动摧毁连接如果闲置时间太长,会自动摧毁对象
    

```

### 2.3 一般性任意python对象的池化

```python
import typing
from universal_object_pool import ObjectPool, AbstractObject
from threadpool_executor_shrink_able import BoundedThreadPoolExecutor
import threading
import time

"""
编码中有时候需要使用一种创建代价很大的对象,而且这个对象不能被多线程同时调用他的操作方法,

比如mysql连接池,socket连接池。
很多这样的例子例典型如mysql的插入,如果多线程高并发同时操作同一个全局connection去插入,很快就会报错了。
那么你可能会为了解决这个问题的方式有如下:

1.你可能这么想,操作mysql的那个函数里面每一次都临时创建mysql连接,函数的末尾关闭coonection,
  这样频繁创建和摧毁连接,无论是服务端还是客户端开销cpu和io高出很多。

2.或者不使用方案1,你是多线程的函数里面用一个全局connection,但是每一个操作mysql的地方都加一个线程锁,
  使得不可能线程1和线程2同时去操作这个connction执行插入,如果假设插入耗时1秒,那么100线程插入1000次要1000秒。

正确的做法是使用mysql连接池库。如果设置开启的连接池中的数量是大于100,100线程插入1000次只需要10秒,节省时间100倍。
mysql连接池已经有知名的连接池包了。如果没有大佬给我们开发mysql连接池库或者一个小众的需求还没有大神针对这个耗时对象开发连接池。
那么可以使用 ObjectPool 实现对象池,连接池就是对象池的一种子集,connection就是pymysql.Connection类型的对象,连接也是对象。
这是万能对象池,所以可以实现webdriver浏览器池。对象并不是需要严格实实在在的外部cocket或者浏览器什么的,也可以是python语言的一个普通对象。
只要这个对象创建代价大,并且它的核心方法是非线程安全的,就很适合使用对象池来使用它。

"""

"""
此模块演示一般常规性任意对象的池化
"""


class Core:  # 一般假设这是个三方包大神写的包里面的某个重要公有类,你需要写的是用has a 模式封装他,你当然也可以使用is a模式来继承它并加上clean_up before_back_to_queue 方法。
    def insert(self, x):
        time.sleep(0.5)
        print(f'插入 {x}')

    def close(self):
        print('关闭连接')


class MockSpendTimeObject(AbstractObject):

    def __init__(self, ):
        time.sleep(0.1)  # 模拟创建对象耗时

        s = 0  # 模拟创建对象耗费cpu
        for j in range(10000 * 500):
            s += j

        self.conn = self.core_obj = Core()  # 这个会造成obj.xx  自动调用 obj.core_obj.xx,很好用。

        self._lock = threading.Lock()

    def do_sth(self, x):
        with self._lock:
            self.conn.insert(x)
            print(f' {x} 假设做某事同一个object只能同时被一个线程调用此方法,是排他的')

    def clean_up(self):
        self.core_obj.close()

    def before_back_to_queue(self, exc_type, exc_val, exc_tb):
        pass


if __name__ == '__main__':
    pool = ObjectPool(object_type=MockSpendTimeObject, object_pool_size=40).set_log_level(10)


    def use_object_pool_run(y):
        """ 第1种 使用对象池是正解"""
        # with ObjectContext(pool) as mock_obj:
        #     mock_obj.do_sth(y)
        with pool.get() as mock_obj:  # type:typing.Union[MockSpendTimeObject,Core]
            # mock_obj.insert(y)  # 可以直接使用core_obj的方法
            mock_obj.do_sth(y)


    def create_object_every_times_for_run(y):
        """第2种 多线程函数内部每次都采用临时创建对象,创建对象代价大,导致总耗时很长"""
        mock_obj = MockSpendTimeObject()
        mock_obj.do_sth(y)


    global_mock_obj = MockSpendTimeObject()
    global_mock_obj.insert(6666)  # 自动拥有self.core_object的方法。


    def use_globle_object_for_run(y):
        """
        第3种 ,多线程中,使用全局唯一对象。少了创建对象的时间,但是操作是独占时间排他的,这种速度是最差的。
        """
        global_mock_obj.do_sth(y)


    t1 = time.perf_counter()
    threadpool = BoundedThreadPoolExecutor(50)

    for i in range(1000):  # 这里随着函数的调用次数越多,对象池优势越明显。假设是运行10万次,三者耗时差距会更大。
        # 这里演示三种调用,1是多线程里用使用对象池 2是使用多线程函数内部每次临时创建关闭对象 3是多线程函数内部使用全局唯一对象。

        threadpool.submit(use_object_pool_run, i)  # 6秒完成
        # threadpool.submit(create_object_every_times_for_run, i)  # 82秒完成
        # threadpool.submit(use_globle_object_for_run, i)  # 耗时100秒

    threadpool.shutdown()
    print(time.perf_counter() - t1)

    time.sleep(100)
    
```

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "universal-object-pool",
    "maintainer": "ydf",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "ydf0509@sohu.com",
    "keywords": "commmon  universal_object_pool",
    "author": "bfzs",
    "author_email": "ydf0509@sohu.com",
    "download_url": "https://files.pythonhosted.org/packages/6f/31/602e7df35c9450bfbebbc5db808b964904fcf91c947c641ade436fc8b57d/universal_object_pool-1.2.tar.gz",
    "platform": "all",
    "description": "## pip install universal_object_pool\r\n\r\n\u6b64\u5305\u80fd\u591f\u5c06\u4e00\u5207\u4efb\u610f\u7c7b\u578b\u7684python\u5bf9\u8c61\u6c60\u5316\uff0c\u662f\u4e07\u80fd\u6c60\uff0c\u9002\u7528\u8303\u56f4\u8fdc\u5927\u4e8e\u5355\u4e00\u7528\u9014\u7684mysql\u8fde\u63a5\u6c60 http\u8fde\u63a5\u6c60\u7b49\u3002\r\n\r\n\u4f7f\u7528\u8fd9\u4e2a\u901a\u7528\u5bf9\u8c61\u6c60\u6846\u67b6\uff0c\u81ea\u5e26\u5b9e\u73b0\u4e864\u4e2a\u5bf9\u8c61\u6c60\u4f8b\u5b50\u3002\u53ef\u4ee5\u76f4\u63a5\u5f00\u7bb1\u7528\u8fd9\u56db\u4e2a\u5bf9\u8c61\u6c60\uff0c\u4e5f\u53ef\u4ee5\u4f5c\u4e3a\u4f8b\u5b50\u5b66\u4e60\u5bf9\u8c61\u6c60\u7528\u6cd5\u3002\r\n\r\ncontrib \u6587\u4ef6\u5939\u81ea\u5e26\u6f14\u793a\u4e864\u4e2a\u5c01\u88c5\uff0c\u5305\u62echttp pymsql webdriver paramiko(\u64cd\u4f5clinux\u7684python\u5305)\u7684\u6c60\u5316\u3002\r\n\r\n<pre style=\"color: darkgreen;font-size: medium\">\r\npython \u901a\u7528\u5bf9\u8c61\u6c60\uff0csocket\u8fde\u63a5\u6c60\u3001mysql\u8fde\u63a5\u6c60\u5f52\u6839\u7ed3\u5e95\u90fd\u662f\u5bf9\u8c61\u6c60\u3002\r\nmysql\u8fde\u63a5\u6c60\u5c31\u662fpymsql.Connection\u7c7b\u578b\u7684\u5bf9\u8c61\u6c60\uff0c\u4e00\u5207\u7686\u5bf9\u8c61\u3002\r\n\u53ea\u662f\u90a3\u4e9b\u5f88\u5e38\u7528\u7684\u529f\u80fd\u7684\u5305\u90fd\u6709\u76f8\u5173\u7684\u6c60\u5e93\uff0c\u6c60\u90fd\u662f\u4e3a\u4ed6\u4eec\u7279\u5b9a\u7684\u529f\u80fd\u5b9a\u5236\u670d\u52a1\u7684\uff0c\u4e0d\u591f\u901a\u7528\u3002\r\n\r\n\u7f16\u7801\u4e2d\u5f88\u591a\u521b\u5efa\u4ee3\u4ef7\u5927\u7684\u5bf9\u8c61\uff08\u8017\u65f6\u8017cpu\uff09\uff0c\u4f46\u662f\u4ed6\u4eec\u7684\u6838\u5fc3\u64cd\u4f5c\u65b9\u6cd5\u53ea\u80fd\u662f\u88ab\u4e00\u4e2a\u7ebf\u7a0b\u5360\u7528\u3002\r\n\r\n\u4f8b\u5982mysql\uff0c\u4f60\u7528\u540c\u4e00\u4e2aconn\u5728\u4e0d\u540c\u7ebf\u7a0b\u540c\u65f6\u53bb\u9ad8\u5e76\u53d1\u53bb\u6267\u884c\u63d2\u5165\u4fee\u6539\u5220\u9664\u64cd\u4f5c\u5c31\u4f1a\u62a5\u9519\uff0c\u800c\u4e14\u5c31\u7b97\u5305\u4e0d\u81ea\u5e26\u62a5\u9519\uff0c\r\n\u5e26\u4e8b\u52a1\u7684\u5373\u4f7f\u4e0d\u62a5\u9519\u5728\u591a\u7ebf\u7a0b\u4e5f\u5bb9\u6613\u6df7\u4e71\uff0c\u4f8b\u5982\u7ebf\u7a0b1\u8981\u5427conn roallback\uff0c\u7ebf\u7a0b2\u8981commit\uff0cconn\u4e2d\u7684\u4e8b\u52a1\u5230\u5e95\u542c\u8c01\u7684\uff1f\r\n\u4f8b\u5982\u4e00\u4e2a\u6d4f\u89c8\u5668\u8981\u5e76\u53d1\u6253\u5f00\u591a\u4e2a\u7f51\u9875\uff0c\u7ebf\u7a0b1\u547d\u4ee4\u6d4f\u89c8\u5668\u6253\u5f00\u65b0\u6d6a\uff0c\u7ebf\u7a0b2\u547d\u4ee4\u6d4f\u89c8\u5668\u6253\u5f00\u641c\u72d0\uff0c\u90a3\u4e48\u6d4f\u89c8\u5668\u5230\u5e95\u542c\u8c01\u7684\uff1f\r\n\u4e00\u4e2ahttp\u94fe\u63a5\u8981\u6253\u5f00\u767e\u5ea6\u65b0\u95fb\u7684\u7b2c\u4e00\u9875\uff0c\u53e6\u5916\u4e00\u4e2a\u7ebf\u7a0b\u53c8\u8ba9\u4ed6\u6253\u5f00\u767e\u5ea6\u65b0\u95fb\u7684\u7b2c\u4e8c\u9875\uff0c\u90a3\u4e48\u8fd9\u4e2asocket\u5230\u5e95\u542c\u8c01\u7684\uff1f\r\n\u89e3\u51b3\u7c7b\u4f3c\u8fd9\u79cd\u6293\u72c2\u7684\u573a\u666f\uff0c\u5982\u679c\u4e0d\u60f3\u518d\u51fd\u6570\u5185\u90e8\u9891\u7e41\u521b\u5efa\u548c\u6467\u6bc1\uff0c\u90a3\u4e48\u5c31\u8981\u4f7f\u7528\u6c60\u5316\u601d\u60f3\u3002\r\n\r\n\r\n\u5982\u679c\u4e00\u4e2a\u5bf9\u8c61\u7684\u521b\u5efa\u4ee3\u4ef7\u5927\u4f8b\u5982\u8017\u65f6\u8017\u8d39\u4ee3\u7801\u884c\u6570\u957f(\u8017cpu)\uff0c\u5e76\u4e14\u4ed6\u7684\u6838\u5fc3\u64cd\u4f5c\u65b9\u6cd5\u662f\u8017\u65f6\u7684\u5e76\u4e14\u662f\u591a\u7ebf\u7a0b\u4e0d\u5b89\u5168\u7684\uff0c\r\n\u90a3\u4e48\u5c31\u6709\u5fc5\u8981\u4f7f\u7528\u6c60\u5316\uff0c\u4f7f\u7a0b\u5e8f\u8fd0\u884c\u901f\u5ea6\u52a0\u5feb\u3002\u548c\u8fd9\u4e2a\u5bf9\u8c61\u4ee3\u8868\u7684\u662f\u4e0d\u662f\u4e00\u4e2asocket\u8fde\u63a5\uff0c\u662f\u4e0d\u662f\u4e00\u4e2a\u6d4f\u89c8\u5668\uff0c\u6ca1\u6709\u4efb\u4f55\u5173\u7cfb\u3002\r\n\r\n\r\n\r\n\r\n</pre>\r\n\r\n\r\n\r\n[\u8fd9\u662f\u4e00\u7bc7\u5f88\u597d\u7684\u535a\u5ba2\uff0c\u8bf4\u660e\u8fde\u63a5\u6c60\u91cd\u8981\u6027: ](https://blog.csdn.net/claroja/article/details/103204159?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166364368816782388023926%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=166364368816782388023926&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-2-103204159-null-null.nonecase&utm_term=python%20%20DBUtils&spm=1018.2226.3001.4450)\r\n\r\n\r\n\r\n```\r\n\r\n\r\n\r\n\r\n\u7f16\u7801\u4e2d\u6709\u65f6\u5019\u9700\u8981\u4f7f\u7528\u4e00\u79cd\u521b\u5efa\u4ee3\u4ef7\u5f88\u5927\u7684\u5bf9\u8c61\uff0c\u800c\u4e14\u8fd9\u4e2a\u5bf9\u8c61\u4e0d\u80fd\u88ab\u591a\u7ebf\u7a0b\u540c\u65f6\u8c03\u7528\u4ed6\u7684\u64cd\u4f5c\u65b9\u6cd5\uff0c\r\n\r\n\u6bd4\u5982mysql\u8fde\u63a5\u6c60\uff0csocket\u8fde\u63a5\u6c60\u3002\r\n\u5f88\u591a\u8fd9\u6837\u7684\u4f8b\u5b50\u4f8b\u5178\u578b\u5982mysql\u7684\u63d2\u5165\uff0c\u5982\u679c\u591a\u7ebf\u7a0b\u9ad8\u5e76\u53d1\u540c\u65f6\u64cd\u4f5c\u540c\u4e00\u4e2a\u5168\u5c40connection\u53bb\u63d2\u5165\uff0c\u5f88\u5feb\u5c31\u4f1a\u62a5\u9519\u4e86\u3002\r\n\u90a3\u4e48\u4f60\u53ef\u80fd\u4f1a\u4e3a\u4e86\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u7684\u65b9\u5f0f\u6709\u5982\u4e0b\uff1a\r\n\r\n1.\u4f60\u53ef\u80fd\u8fd9\u4e48\u60f3\uff0c\u64cd\u4f5cmysql\u7684\u90a3\u4e2a\u51fd\u6570\u91cc\u9762\u6bcf\u4e00\u6b21\u90fd\u4e34\u65f6\u521b\u5efamysql\u8fde\u63a5\uff0c\u51fd\u6570\u7684\u672b\u5c3e\u5173\u95edcoonection\uff0c\r\n  \u8fd9\u6837\u9891\u7e41\u521b\u5efa\u548c\u6467\u6bc1\u8fde\u63a5\uff0c\u65e0\u8bba\u662f\u670d\u52a1\u7aef\u8fd8\u662f\u5ba2\u6237\u7aef\u5f00\u9500cpu\u548cio\u9ad8\u51fa\u5f88\u591a\u3002\r\n\r\n2.\u6216\u8005\u4e0d\u4f7f\u7528\u65b9\u68481\uff0c\u4f60\u662f\u591a\u7ebf\u7a0b\u7684\u51fd\u6570\u91cc\u9762\u7528\u4e00\u4e2a\u5168\u5c40connection\uff0c\u4f46\u662f\u6bcf\u4e00\u4e2a\u64cd\u4f5cmysql\u7684\u5730\u65b9\u90fd\u52a0\u4e00\u4e2a\u7ebf\u7a0b\u9501\uff0c\r\n  \u4f7f\u5f97\u4e0d\u53ef\u80fd\u7ebf\u7a0b1\u548c\u7ebf\u7a0b2\u540c\u65f6\u53bb\u64cd\u4f5c\u8fd9\u4e2aconnction\u6267\u884c\u63d2\u5165\uff0c\u5982\u679c\u5047\u8bbe\u63d2\u5165\u8017\u65f61\u79d2\uff0c\u90a3\u4e48100\u7ebf\u7a0b\u63d2\u51651000\u6b21\u89811000\u79d2\u3002\r\n\r\n\u6b63\u786e\u7684\u505a\u6cd5\u662f\u4f7f\u7528mysql\u8fde\u63a5\u6c60\u5e93\u3002\u5982\u679c\u8bbe\u7f6e\u5f00\u542f\u7684\u8fde\u63a5\u6c60\u4e2d\u7684\u6570\u91cf\u662f\u5927\u4e8e100\uff0c100\u7ebf\u7a0b\u63d2\u51651000\u6b21\u53ea\u9700\u898110\u79d2\uff0c\u8282\u7701\u65f6\u95f4100\u500d\u3002\r\nmysql\u8fde\u63a5\u6c60\u5df2\u7ecf\u6709\u77e5\u540d\u7684\u8fde\u63a5\u6c60\u5305\u4e86\u3002\u5982\u679c\u6ca1\u6709\u5927\u4f6c\u7ed9\u6211\u4eec\u5f00\u53d1mysql\u8fde\u63a5\u6c60\u5e93\u6216\u8005\u4e00\u4e2a\u5c0f\u4f17\u7684\u9700\u6c42\u8fd8\u6ca1\u6709\u5927\u795e\u9488\u5bf9\u8fd9\u4e2a\u8017\u65f6\u5bf9\u8c61\u5f00\u53d1\u8fde\u63a5\u6c60\u3002\r\n\u90a3\u4e48\u53ef\u4ee5\u4f7f\u7528 ObjectPool \u5b9e\u73b0\u5bf9\u8c61\u6c60\uff0c\u8fde\u63a5\u6c60\u5c31\u662f\u5bf9\u8c61\u6c60\u7684\u4e00\u79cd\u5b50\u96c6\uff0cconnection\u5c31\u662fpymysql.Connection\u7c7b\u578b\u7684\u5bf9\u8c61\uff0c\u8fde\u63a5\u4e5f\u662f\u5bf9\u8c61\u3002\r\n\u8fd9\u662f\u4e07\u80fd\u5bf9\u8c61\u6c60\uff0c\u6240\u4ee5\u53ef\u4ee5\u5b9e\u73b0webdriver\u6d4f\u89c8\u5668\u6c60\u3002\u5bf9\u8c61\u5e76\u4e0d\u662f\u9700\u8981\u4e25\u683c\u5b9e\u5b9e\u5728\u5728\u7684\u5916\u90e8cocket\u6216\u8005\u6d4f\u89c8\u5668\u4ec0\u4e48\u7684\uff0c\u4e5f\u53ef\u4ee5\u662fpython\u8bed\u8a00\u7684\u4e00\u4e2a\u666e\u901a\u5bf9\u8c61\u3002\r\n\u53ea\u8981\u8fd9\u4e2a\u5bf9\u8c61\u521b\u5efa\u4ee3\u4ef7\u5927\uff0c\u5e76\u4e14\u5b83\u7684\u6838\u5fc3\u65b9\u6cd5\u662f\u975e\u7ebf\u7a0b\u5b89\u5168\u7684\uff0c\u5c31\u5f88\u9002\u5408\u4f7f\u7528\u5bf9\u8c61\u6c60\u6765\u4f7f\u7528\u5b83\u3002\r\n\r\n\r\n\r\n\r\n```\r\n\r\n## 1.\u5e38\u95ee\u95ee\u9898\u56de\u7b54\r\n\r\n### 1.1 \u5bf9\u8c61\u6c60\u662f\u7ebf\u7a0b\u5b89\u5168\u7684\u5417\uff1f\r\n\r\n```\r\n\u8fd9\u4e2a\u95ee\u9898\u725b\u5934\u4e0d\u5bf9\u9a6c\u5634 \uff0c\u5bf9\u8c61\u6c60\u5c31\u662f\u4e3a\u591a\u7ebf\u7a0b\u6216\u8005\u5e76\u53d1\u800c\u751f\u7684\u3002\r\n\u4f60\u60f3\u4e00\u4e0b\uff0c\u5982\u679c\u4f60\u7684\u64cd\u4f5c\u53ea\u6709\u4e00\u4e2a\u4e3b\u7ebf\u7a0b\uff0c\u90a3\u76f4\u63a5\u7528\u4e00\u4e2a\u5bf9\u8c61\u4e00\u76f4\u7528\u5c31\u662f\u4e86\uff0c\u53cd\u6b63\u4e0d\u4f1a\u9047\u5230\u591a\u7ebf\u7a0b\u8981\u4f7f\u7528\u540c\u4e00\u4e2a\u5bf9\u8c61\u3002\r\n\r\n\u4f60\u82b1\u8111\u888b\u60f3\u60f3\uff0c\u5982\u679c\u4f60\u7684\u4ee3\u7801\u662f\u4e3b\u7ebf\u7a0b\u5355\u7ebf\u7a0b\u7684\uff0c\u4f60\u6709\u5fc5\u8981\u7528dbutils\u6765\u641emysql\u8fde\u63a5\u6c60\u5417\u3002\r\n\u76f4\u63a5\u7528pymysql\u7684conn\u4e0d\u662f\u66f4\u7b80\u5355\u66f4\u9999\u5417\u3002\r\nweb\u540e\u7aef\u662fuwsgi gunicorn\u6765\u81ea\u52a8\u5f00\u591a\u7ebf\u7a0b\u6216\u8005\u534f\u7a0b\u662f\u81ea\u52a8\u5e76\u53d1\u7684\uff0c\u867d\u7136\u4f60\u6ca1\u4eb2\u81ea\u5f00\u591a\u7ebf\u7a0b\uff0c\u4f46\u4e5f\u662f\u591a\u7ebf\u7a0b\u7684\uff0c\u9700\u8981\u4f7f\u7528\u8fde\u63a5\u6c60\u3002\r\n\r\n\u4efb\u4f55\u53eb\u6c60\u7684\u4e1c\u897f\u90fd\u662f\u4e3a\u5e76\u53d1\u800c\u751f\u7684\uff0c\u5982\u679c\u4e0d\u80fd\u591a\u7ebf\u7a0b\u5b89\u5168\uff0c\u90a3\u5b58\u5728\u7684\u610f\u4e49\u76ee\u7684\u4f55\u5728\uff1f\r\n\r\n```\r\n\r\n### 1.2 \u5bf9\u8c61\u6c60 \u8fde\u63a5\u6c60 \u7ebf\u7a0b\u6c60\u6709\u4ec0\u4e48\u533a\u522b\u3002\r\n\r\n```\r\n\u8fde\u63a5\u6c60\u5c31\u662f\u5bf9\u8c61\u6c60\uff0c\u8fde\u63a5\u6c60\u4e00\u822c\u662f\u94fe\u63a5\u6570\u636e\u5e93 \u6216\u8005\u4e2d\u95f4\u4ef6\u6216\u8005socket\u7684\u5bf9\u8c61\uff0c\u6bd4\u5982mysql\u7684connection\uff0c\u6709\u7684\u5bf9\u8c61\u5e76\u4e0d\u662f\u94fe\u63a5\u4ec0\u4e48socket\uff0c\r\n\u4f46\u662f\u521b\u5efa\u4ee3\u4ef7\u5927\uff0c\u65b9\u6cd5\u975e\u7ebf\u7a0b\u5b89\u5168\uff0c\u5c31\u662f\u5bf9\u8c61\u6c60\u3002\u8fde\u63a5\u6c60\u662f\u5bf9\u8c61\u6c60\u7684\u4e00\u4e2a\u5b50\u96c6\u3002\r\n\r\n\u7ebf\u7a0b\u6c60\u548c\u5bf9\u8c61\u6c60\u5173\u7cfb\u5f88\u5c0f\uff0c\u6b64\u5bf9\u8c61\u6c60\u53ef\u4ee5\u5b9e\u73b0\u4e86\u4e00\u5207\u5bf9\u8c61\u6c60\u5316\uff0c\u4f46\u5e76\u4e0d\u80fd\u62ff\u6765\u5b9e\u73b0\u7ebf\u7a0b\u6c60\u3002\r\n\u5982\u679c\u8981\u770b\u7ebf\u7a0b\u6c60\uff0chttps://github.com/ydf0509/threadpool_executor_shrink_able \u6b64\u9879\u76ee\u5b9e\u73b0\u4e86\u7ebf\u7a0b\u6c60\u3002\r\n\r\n\r\nhttps://blog.csdn.net/Alan_Mathison_Turing/article/details/78512410 \u8fd9\u4e2a\u8bb2\u5f97\u5bf9\u8c61\u6c60\u548c\u7ebf\u7a0b\u6c60\u533a\u522b\uff0c\u8bb2\u7684\u4e0d\u9519\u3002\r\n\r\n\u4e00\u4e2a\u5bf9\u8c61\u6c60\u7684\u57fa\u672c\u884c\u4e3a\u5305\u62ec\uff1a\r\n\r\n\u521b\u5efa\u5bf9\u8c61newObject()\r\n\u501f\u53d6\u5bf9\u8c61getObject()\r\n\u5f52\u8fd8\u5bf9\u8c61freeObject()\r\n\r\n\u7ebf\u7a0b\u6c60\r\n\u9996\u5148\u6446\u51fa\u7ed3\u8bba\uff1a\u7ebf\u7a0b\u6c60\u7cc5\u5408\u4e86\u5bf9\u8c61\u6c60\u6a21\u578b\uff0c\u4f46\u662f\u6838\u5fc3\u539f\u7406\u662f\u751f\u4ea7\u8005-\u6d88\u8d39\u8005\u6a21\u578b\u3002\r\n\r\n\u7ebf\u7a0b\u6c60\u5e76\u4e0d\u662f\u50cf\u591a\u7ebf\u7a0b\u628a\u67d0\u4e2a\u7ebf\u7a0b\u501f\u51fa\u53bb\u4f7f\u7528\u7136\u540e\u5229\u7528\u5b8c\u4e86\u5f52\u8fd8\uff0c\u7ebf\u7a0b\u6c60\u91cc\u9762\u7684\u7ebf\u7a0b\u90fd\u662fwhile true\u7684\u6b7b\u5faa\u73af\uff0c\r\n\u4e0d\u4f1a\u50cf\u5bf9\u8c61\u6c60\u4f8b\u5982mysql\u7684conn\u67e5\u8be2\u4e00\u4e0b\u51e0\u5341\u6beb\u79d2\u949f\u5c31\u7528\u5b8c\u4e86\uff0c\u7ebf\u7a0b\u6c60\u91cc\u9762\u7684\u7ebf\u7a0b\u5bf9\u8c61\u662f\u6c38\u4e0d\u7ed3\u675f\u7684\uff0c\u6ca1\u6709\u501f\u51fa\u53bb\u4f7f\u7528\u7528\u5b8c\u4e86\u540e\u5f52\u8fd8\u8fd9\u79cd\u4e8b\u60c5\u3002\r\n\r\n\u6240\u4ee5\u4e0d\u80fd\u60f3\u7740\u5b66\u4e60\u6c60\u5316mysql connection\u6216\u8005selnium\u7684driver\uff0c\u4e5f\u628athreading.Thread\u6c60\u5316\u5462\uff0cThread\u5bf9\u8c61\u968f\u7740run\u65b9\u6cd5\u7684\u7ed3\u675f\u5c31\u4f1a\u81ea\u52a8\u6467\u6bc1\u4e86\r\n\uff0c\u65e0\u6cd5\u4eba\u4e3a\u7684\u4f7fThread\u4e0d\u6467\u6bc1\uff0c\u4e5f\u5c31\u662f\u8bf4\u7ebf\u7a0b\u662f\u968f\u7740run\u65b9\u6cd5\u8fd0\u884c\u5b8c\u6210\u5c31\u81ea\u52a8\u7ed3\u675f\u4e86\u4e0d\u53ef\u653e\u5230\u6c60\u5b50\u91cc\u9762\u53cd\u590d\u62ff\u51fa\u6765\u77ed\u6682\u5229\u7528\uff0c\u90a3\u4e48\u7ebf\u7a0b\u6c60\u662f\u5982\u4f55\u590d\u7528\u7ebf\u7a0b\u7684\u5462\uff1f\r\n\u56e0\u4e3a\u4e0a\u9762\u8bf4\u4e86\u7ebf\u7a0b\u968f\u7740run\u65b9\u6cd5\u8fd0\u884c\u5b8c\u6210\u5c31\u81ea\u52a8\u7ed3\u675f\u4e86\u662f\u4e00\u6b21\u6027\u7684\uff0c\u90a3\u4e48\u4e3b\u8981\u662f\u5c31\u662f\u628a\u7ebf\u7a0b\u6c60\u7684\u6bcf\u4e2a\u7ebf\u7a0b\u7684run\u65b9\u6cd5\u8bbe\u8ba1\u6210\u65e0\u9650\u8499\u853d\u6b7b\u5faa\u73af\u7684while 1\u6c38\u4e0d\u7ed3\u675f\u5c31\u80fd\u89e3\u51b3\u590d\u7528\u95ee\u9898\u4e86\uff0c\r\n\u6bcf\u4e2a\u7ebf\u7a0b\u7684run\u65b9\u6cd5\u90fd\u662f\u5728while 1 \u91cc\u9762 fun,args = queue.get(block=True),\u6bcf\u53d6\u51fa\u4e00\u4e2a\u4efb\u52a1\u540e\u5c31\u5728\u5f53\u524d\u7ebf\u7a0b\u6267\u884c fun(*agrs)\uff0c\u6240\u4ee5\u7ebf\u7a0b\u4e00\u76f4\u662f\u90a3\u4e2a\u7ebf\u7a0b\uff0c\r\n\u4f46\u662f\u53ef\u4ee5\u8fd0\u884c\u7684\u51fd\u6570\u548c\u51fd\u6570\u53c2\u6570\u5374\u662f\u65e0\u9650\u53ef\u80fd\u7684\u3002\r\n\u4efb\u4f55\u7ebf\u7a0b\u6c60\u5b9e\u73b0\u90fd\u662f\u6709\u4e2aqueue\uff0c\u751f\u4ea7\u8005\u5f80queue\u91cc\u9762submit\u4efb\u52a1\uff0c\r\n\u6d88\u8d39\u8005\u662f\u4f8b\u5982100\u4e2a\u7ebf\u7a0b\uff0c\u6bcf\u4e2a\u7ebf\u7a0b\u91cc\u9762\u8dd1\u7684\u51fd\u6570\u90fd\u662fwhile True\u7684\u6b7b\u5faa\u73af\u51fd\u6570\uff0cwhile 1\u91cc\u9762\u4e0d\u65ad\u7684\u7528queue.get\u4ecequeue\u91cc\u9762\u62c9\u53d6\u4efb\u52a1\uff0c\r\n\u62c9\u53d6\u4e00\u4e2a\u4efb\u52a1\uff0c\u5c31\u7acb\u5373fun(x,y)\u8fd9\u4e48\u53bb\u8fd0\u884c\u3002\u4efb\u4f55\u8bed\u8a00\u4efb\u4f55\u4eba\u5b9e\u73b0\u7ebf\u7a0b\u6c60\u4e00\u5b9a\u662f\u8fd9\u4e2a\u601d\u8def\u8fd9\u4e48\u5199\u7684\uff0c\u6ca1\u6709\u4f8b\u5916\u3002\r\n\r\n\u8bf4\u5230\u6b7b\u5faa\u73af\u90a3\u5c31\u5f88\u6709\u8da3\u4e86\uff0c\u8fd9\u91cc\u662f\u7ebf\u7a0b\u6c60\u8bbe\u8ba1\u7684\u4e00\u4e2a\u96be\u70b9\u91cd\u70b9\uff0c\u5982\u679cwhile True\u6b7b\u5faa\u73af\uff0c\u90a3\u7ebf\u7a0b\u6c60\u4e0d\u662f\u65e0\u654c\u4e86\u65e0\u89e3\u4e86\uff0c\u4ee3\u7801\u90a3\u4e0d\u662f\u6c38\u8fdc\u7ed3\u675f\u4e0d\u4e86\uff1f\r\n\u7ebf\u7a0b\u6c60\u91cc\u9762\u8bbe\u8ba1\u7684\u4e00\u4e2a\u96be\u70b9\u5c31\u5305\u62ec\u8fd9\u91cc\uff0c\u6240\u4ee5\u5f88\u591a\u4eba\u5199\u7684\u7ebf\u7a0b\u6c60\u90fd\u5f88\u96be\u7528\uff0c\u8981\u4e48\u7a0b\u5e8f\u6c38\u4e0d\u7ed3\u675f\uff0c\u8981\u4e48\u8bbe\u8ba1\u6210\u4e86\u7ebf\u7a0b\u6c60\u7684queue\u91cc\u9762\u8fd8\u6709\u4efb\u52a1\u6ca1\u5b8c\u6210\uff0c\r\n\u7a0b\u5e8f\u5c31\u7ed3\u675f\u4e86\uff0c\u6240\u4ee5pool.submit\uff0c\u5f88\u591a\u4eba\u641e\u7684\u7ebf\u7a0b\u6c60\u5728\u4ee3\u7801\u6700\u7ed3\u5c3e\u8981\u52a0\u4e0apool.termit\u4ec0\u4e48\u73a9\u610f\u7684\uff0c\u53ef\u4ee5\u767e\u5ea6\u535a\u5ba2\u56edpython\u7ebf\u7a0b\u6c60\u597d\u591a\u5c31\u662f\u8fd9\u6837\u7684\uff0c\r\n\u6ca1\u6709\u51e0\u4e2a\u4eba\u8bbe\u8ba1\u7684\u624b\u5199\u7ebf\u7a0b\u6c60\u8fbe\u5230\u4e86 concurrent.futures.Threadpoolexecutor\u90a3\u4e48\u597d\u7528\u7684\u7a0b\u5ea6\uff0c\u6700\u4e3b\u8981\u662f\u4e0d\u4e86\u89e3\u5b88\u62a4\u7ebf\u7a0b\uff0c\r\n\u5f88\u591a\u4eba\u90fd\u662f\u641e\u7684\u975e\u5b88\u62a4\u7ebf\u7a0b\uff0c\u5bfc\u81f4\u53d1\u660e\u7684\u7ebf\u7a0b\u6c60\u6bd4\u5185\u7f6e\u7684concurrent.futures.Threadpoolexecutor\u597d\u7528\u7a0b\u5ea6\u5dee\u5341\u4e07\u516b\u5343\u91cc\u3002\r\n\u5982\u679c\u628awhile 1\u6b7b\u5faa\u73af\u7684\u7ebf\u7a0b\u8bbe\u7f6e\u4e3a\u5b88\u62a4\u7ebf\u7a0b\uff0c\u90a3\u4e48\u5f53\u4e3b\u7ebf\u7a0b\u7ed3\u675f\u540e\uff0c\u5b88\u62a4\u7ebf\u7a0b\u5c31\u4f1a\u81ea\u52a8\u968f\u7a0b\u5e8f\u7ed3\u675f\u4e86\u3002\u5f53\u7136\u4e86\u5149\u8bbe\u7f6e\u5b88\u62a4\u7ebf\u7a0b\u8fd8\u4e0d\u591f\uff0c\r\n\u5982\u679c\u4e3b\u7ebf\u7a0b\u628a\u4efb\u52a1\u90fdsubmit\u5230queue\u91cc\u9762\u4e86\uff0c\u5b9e\u9645\u4e0a\u7ebf\u7a0b\u6c60\u5e94\u8be5\u8fd8\u9700\u8981\u8fd0\u884cqueue\u91cc\u9762\u7684\u4efb\u52a1\uff0c\u6240\u4ee5\u8fd8\u9700\u8981\u52a0\u4e2a\u5224\u65ad\uff0c\u8981\u52a0\u4e0a atexit.register\u7684\u94a9\u5b50\uff0c\r\n\u8ba9\u4efb\u52a1\u6267\u884c\u5b8c\u6210\u624d\u5173\u95ed\u3002\u8bbe\u8ba1\u4e00\u4e2a\u597d\u7528\u7684\u7ebf\u7a0b\u6c60\u8fd8\u662f\u5f88\u96be\u7684\uff0c\u8bbe\u8ba1\u4e00\u4e2a\u6b7b\u5faa\u73af\u5bfc\u81f4\u4ee3\u7801\u6c38\u4e0d\u80fd\u81ea\u52a8\u7ed3\u675f\u7684\u7ebf\u7a0b\u6c60\u5c31\u7b80\u5355\u5f88\u591a\u4e86\u3002\r\n\u6bd4\u5982\u8fd9\u4e2a\u7ebf\u7a0b\u6c60  https://github.com/mingxiaoHe/ThreadPool/blob/master/threadpool.py \u8bbe\u8ba1\u5f97\u5f88\u60b2\u50ac\uff0c\r\n\u5fc5\u987b\u624b\u52a8\u5728\u6574\u4e2a\u9879\u76ee\u6700\u672b\u672a\u52a0\u4e0a pool.close(),\u800c\u4e14\u4e0d\u80fd\u52a0\u5728\u4ee3\u7801\u4e2d\u95f4\uff0c\u56e0\u4e3a\u52a0\u8f7d\u4e2d\u95f4\u4f1a\u5bfc\u81f4\u5982\u679c\u4e4b\u540e\u7ee7\u7eed\u63d0\u4ea4\u4efb\u52a1\u5c31\u6ca1\u7ebf\u7a0b\u80fd\u529b\u6267\u884c\u4e86\uff0c\u592a\u96be\u4e86\u7528\u4e86\u8fd9\u79cd\r\n\u4e3b\u8981\u662f\u4e0d\u77e5\u9053\u5b88\u62a4\u7ebf\u7a0b\u7528\u9014\u3002\r\n\r\n\u8fd8\u6709\u8fd9\u4e2a https://github.com/shengqi158/ThreadPool/blob/master/ThreadPool.py\uff0c\u6700\u672b\u672a\u8981\u52a0\u4e0athreadpool.task_join()\uff0c\r\n\u5f88\u591a\u5c01\u88c5\u7684\u9700\u8981\u6700\u6700\u672b\u5c3e\u52a0\u4e00\u53e5\uff0c\u4e3b\u8981\u662f\u4e0d\u77e5\u9053\u5b88\u62a4\u7ebf\u7a0b\u7528\u9014\u3002\r\n\r\n\r\n\u7ebf\u7a0b\u6c60\u7684\u601d\u8def\u4e8e\u5bf9\u8c61\u6c60\u51e0\u4e4e\u5b8c\u5168\u4e0d\u540c\u3002\r\n\r\n\r\n\r\n```\r\n\r\n## 2.\u5229\u7528\u5bf9\u8c61\u6c60\u6765\u5c01\u88c5\u4efb\u610f\u7c7b\u578b\u7684\u6c60\u6f14\u793a\r\n\r\ncontrib \u6587\u4ef6\u5939\u81ea\u5e26\u6f14\u793a\u4e864\u4e2a\u5c01\u88c5\uff0c\u5305\u62echttp pymsql webdriver paramiko(\u64cd\u4f5clinux\u7684python\u5305)\u7684\u6c60\u5316\u3002\r\n\r\n### 2.0 \u4f8b\u5982\u4f7f\u7528\u4e07\u80fd\u5bf9\u8c61\u6c60\u5305\u5b9e\u73b0\u7684 nb_http_client\r\n\r\n[nb_http_client](https://github.com/ydf0509/nb_http_client)\r\n\r\nnb_http_client \u662f python \u53f2\u4e0a\u6027\u80fd\u6700\u5f3a\u7684http\u5ba2\u6237\u7aef\uff0c\u6bd4\u4efb\u610f\u81ea\u5e26\u548c\u4e09\u65b9\u8bf7\u6c42\u5305\u5feb\u5f88\u591a\u500d\u3002\r\n\r\n### 2.1 mysql \u6c60\u5316\r\n\r\n\u4ee5\u4e0b\u662fpymysql_pool\u7684\u6c60\u5316\u4ee3\u7801\uff0c\u4f7f\u7528has a\u6a21\u5f0f\u5c01\u88c5\u7684PyMysqlOperator\u5bf9\u8c61\uff0c\u4f60\u4e5f\u53ef\u4ee5\u4f7f\u7528is a\u6765\u7ee7\u627f\u65b9\u5f0f\u6765\u5199\uff0c\u4f46\u8981\u5b9e\u73b0clean_up\u7b49\u65b9\u6cd5\u3002\r\n\r\n```python\r\nimport copy\r\n\r\nimport pymysql\r\nimport typing\r\nfrom universal_object_pool import ObjectPool, AbstractObject\r\nfrom threadpool_executor_shrink_able import BoundedThreadPoolExecutor\r\nimport threading\r\nimport time\r\nimport decorator_libs\r\n\r\n\"\"\"\r\n\u8fd9\u4e2a\u662f\u771f\u6b63\u7684\u7528pymsql\u5b9e\u73b0\u8fde\u63a5\u6c60\u7684\u4f8b\u5b50\uff0c\u5b8c\u5168\u6ca1\u6709\u4f9d\u8d56dbutils\u5305\u5b9e\u73b0\u7684\u8fde\u63a5\u6c60\u3002\r\n\u6bd4dbutils\u55e8\u597d\u7528\uff0c\u5b9e\u9645\u4f7f\u7528\u65f6\u5019\u4e0d\u9700\u8981\u64cd\u4f5ccursor\u7684\u5efa\u7acb\u548c\u5173\u95ed\u3002\r\n\r\ndbutils\u5b98\u65b9\u7528\u6cd5\u662f\r\n\r\npool= PooledDB()\r\ndb = pool.connection()\r\ncur = db.cursor()\r\ncur.execute(...)\r\nres = cur.fetchone()\r\ncur.close()  # or del cur\r\ndb.close()  # or del db\r\n\r\n\"\"\"\r\n\r\n\r\nclass PyMysqlOperator(AbstractObject):\r\n    error_type_list_set_not_available = []  # \u51fa\u4e86\u7279\u5b9a\u7c7b\u578b\u7684\u9519\u8bef\uff0c\u53ef\u4ee5\u8bbe\u7f6e\u5bf9\u8c61\u5df2\u7ecf\u65e0\u6548\u4e0d\u53ef\u7528\u4e86\uff0c\u4e0d\u5f52\u8fd8\u5230\u961f\u5217\u91cc\u9762\u3002\r\n\r\n    # error_type_list_set_not_available = [pymysql.err.InterfaceError]\r\n\r\n    def __init__(self, host='192.168.6.130', user='root', password='123456', cursorclass=pymysql.cursors.DictCursor,\r\n                 autocommit=False, **pymysql_connection_kwargs):\r\n        in_params = copy.copy(locals())\r\n        in_params.update(pymysql_connection_kwargs)\r\n        in_params.pop('self')\r\n        in_params.pop('pymysql_connection_kwargs')\r\n        self.conn = pymysql.Connection(**in_params)\r\n\r\n    \"\"\" \u4e0b\u97623\u4e2a\u662f\u91cd\u5199\u7684\u65b9\u6cd5\"\"\"\r\n\r\n    def clean_up(self):  # \u5982\u679c\u4e00\u4e2a\u5bf9\u8c61\u6700\u8fd130\u5206\u949f\u5185\u6ca1\u88ab\u4f7f\u7528\uff0c\u90a3\u4e48\u5bf9\u8c61\u6c60\u4f1a\u81ea\u52a8\u5c06\u5bf9\u8c61\u6467\u6bc1\u5e76\u4ece\u6c60\u4e2d\u5220\u9664\uff0c\u4f1a\u81ea\u52a8\u8c03\u7528\u5bf9\u8c61\u7684clean_up\u65b9\u6cd5\u3002\r\n        self.conn.close()\r\n\r\n    def before_use(self):\r\n        self.cursor = self.conn.cursor()\r\n        self.core_obj = self.cursor  # \u8fd9\u4e2a\u662f\u4e3a\u4e86operator\u5bf9\u8c61\u81ea\u52a8\u62e5\u6709cursor\u5bf9\u8c61\u7684\u6240\u6709\u65b9\u6cd5\u3002\r\n\r\n    def before_back_to_queue(self, exc_type, exc_val, exc_tb):\r\n        if exc_type:\r\n            self.conn.rollback()\r\n        else:\r\n            self.conn.commit()\r\n        self.cursor.close()  # \u4e5f\u53ef\u4ee5\u4e0d\u8981\uff0c\u56e0\u4e3a\u6bcf\u6b21\u7684cusor\u90fd\u662f\u4e0d\u4e00\u6837\u7684\u3002\r\n\r\n    \"\"\"\u4ee5\u4e0b\u53ef\u4ee5\u81ea\u5b9a\u4e49\u5176\u4ed6\u65b9\u6cd5\u3002\r\n    \u56e0\u4e3a\u8bbe\u7f6e\u4e86self.core_obj = self.cursor \uff0c\u7236\u7c7b\u91cd\u5199\u4e86__getattr__,\u6240\u4ee5\u6b64\u5bf9\u8c61\u81ea\u52a8\u62e5\u6709cursor\u5bf9\u8c61\u7684\u6240\u6709\u65b9\u6cd5,\u5982\u679c\u662f\u540c\u540d\u540c\u610f\u4e49\u7684\u65b9\u6cd5\u4e0d\u9700\u8981\u4e00\u4e2a\u4e2a\u91cd\u5199\u3002\r\n    \"\"\"\r\n\r\n    def execute(self, query, args):\r\n        \"\"\"\r\n        \u8fd9\u4e2aexecute\u7531\u4e8e\u65b9\u6cd5\u540d\u548c\u5165\u53c2\u548c\u903b\u8f91\u4e0e\u5b98\u65b9\u4e00\u6a21\u4e00\u6837\uff0c\u53ef\u4ee5\u4e0d\u9700\u8981\uff0c\u56e0\u4e3a\u8bbe\u7f6e\u4e86core_obj\u540e\uff0coperator\u5bf9\u8c61\u81ea\u52a8\u62e5\u6709cursor\u5bf9\u8c61\u7684\u6240\u6709\u65b9\u6cd5\uff0c\u53ef\u4ee5\u628a\u8fd9\u4e2a\u65b9\u6cd5\u6ce8\u91ca\u4e86\u7136\u540e\u6d4b\u8bd5\u8fd0\u884c\u4e0d\u53d7\u5f71\u54cd\u3002\r\n        :param query:\r\n        :param args:\r\n        :return:\r\n        \"\"\"\r\n        return self.cursor.execute(query, args)\r\n\r\n\r\nif __name__ == '__main__':\r\n    mysql_pool = ObjectPool(object_type=PyMysqlOperator, object_pool_size=100, object_init_kwargs={'port': 3306})\r\n\r\n\r\n    def test_update(i):\r\n        sql = f'''\r\n            INSERT INTO db1.table1(uname ,age)\r\n        VALUES(\r\n            %s ,\r\n            %s)\r\n        ON DUPLICATE KEY UPDATE\r\n            uname = values(uname),\r\n            age = if(values(age)>age,values(age),age);\r\n        '''\r\n        with mysql_pool.get(\r\n                timeout=2) as operator:  # type: typing.Union[PyMysqlOperator,pymysql.cursors.DictCursor] #\u5229\u4e8e\u8865\u5168\r\n            print(id(operator.cursor), id(operator.conn))\r\n            operator.execute(sql, args=(f'name_{i}', i * 4))\r\n            print(\r\n                operator.lastrowid)  # opererator \u81ea\u52a8\u62e5\u6709 operator.cursor \u7684\u6240\u6709\u65b9\u6cd5\u548c\u5c5e\u6027\u3002 opererator.methodxxx \u4f1a\u81ea\u52a8\u8c03\u7528 opererator.cursor.methodxxx\r\n\r\n\r\n    operator_global = PyMysqlOperator()\r\n\r\n\r\n    def test_update_multi_threads_use_one_conn(i):\r\n        \"\"\"\r\n        \u8fd9\u4e2a\u662f\u4e2a\u9519\u8bef\u7684\u4f8b\u5b50\uff0c\u591a\u7ebf\u7a0b\u8fd0\u884c\u6b64\u51fd\u6570\u4f1a\u75af\u72c2\u62a5\u9519,\u5355\u7ebf\u7a0b\u4e0d\u62a5\u9519\r\n        \u8fd9\u4e2a\u5982\u679c\u8fd0\u884c\u5728\u591a\u7ebf\u7a0b\u540c\u65f6\u64cd\u4f5c\u540c\u4e00\u4e2aconn\uff0c\u5c31\u4f1a\u75af\u72c2\u62a5\u9519\u3002\u6240\u4ee5\u8981\u4e48\u72e0low\u7684\u4f7f\u7528\u4e34\u65f6\u9891\u7e41\u5728\u51fd\u6570\u5185\u90e8\u6bcf\u6b21\u521b\u5efa\u548c\u6467\u6bc1mysql\u8fde\u63a5\uff0c\u8981\u4e48\u4f7f\u7528\u8fde\u63a5\u6c60\u3002\r\n        :param i:\r\n        :return:\r\n        \"\"\"\r\n        sql = f'''\r\n            INSERT INTO db1.table1(uname ,age)\r\n        VALUES(\r\n            %s ,\r\n            %s)\r\n        ON DUPLICATE KEY UPDATE\r\n            uname = values(uname),\r\n            age = if(values(age)>age,values(age),age);\r\n        '''\r\n\r\n        operator_global.before_use()\r\n        print(id(operator_global.cursor), id(operator_global.conn))\r\n        operator_global.execute(sql, args=(f'name_{i}', i * 3))\r\n        operator_global.cursor.close()\r\n        operator_global.conn.commit()\r\n\r\n\r\n    thread_pool = BoundedThreadPoolExecutor(20)\r\n    with decorator_libs.TimerContextManager():\r\n        for x in range(200000, 300000):\r\n            thread_pool.submit(test_update, x)\r\n            # thread_pool.submit(test_update_multi_threads_use_one_conn, x)\r\n        thread_pool.shutdown()\r\n    time.sleep(10000)  # \u8fd9\u4e2a\u53ef\u4ee5\u6d4b\u8bd5\u9a8c\u8bc1\uff0c\u6b64\u5bf9\u8c61\u6c60\u4f1a\u81ea\u52a8\u6467\u6bc1\u8fde\u63a5\u5982\u679c\u95f2\u7f6e\u65f6\u95f4\u592a\u957f\uff0c\u4f1a\u81ea\u52a8\u6467\u6bc1\u5bf9\u8c61\r\n\r\n\r\n``` \r\n\r\n### 2.2 linux \u64cd\u4f5c\u795e\u5e93 paramiko \u7684\u6c60\u5316\uff0c\u4f8b\u5982\u53ef\u4ee5\u5927\u5e45\u5ea6\u52a0\u5feb\u6587\u4ef6\u4f20\u8f93\u548c\u5927\u5e45\u5ea6\u52a0\u5feb\u6709io\u7684\u547d\u4ee4\u3002\r\n\r\n\u6bd4\u5982\u6709\u5f88\u591a\u51e0kb\u7684\u5c0f\u6587\u4ef6\u9700\u8981\u4e0a\u4f20\uff0c\u5bf9\u8c61\u6c60 + \u7ebf\u7a0b\u6c60\u53ef\u4ee5\u5927\u5e45\u5ea6\u63d0\u5347\u4e0a\u4f20\u901f\u5ea6\r\n\r\n\u6bd4\u5982\u8ba9linux\u6267\u884c\u6709io\u8017\u65f6\u7684curl\u547d\u4ee4\uff0c\u5bf9\u8c61\u6c60 + \u7ebf\u7a0b\u6c60\u53ef\u4ee5\u5927\u5e45\u5ea6\u63d0\u5347\u547d\u4ee4\u6267\u884c\u6548\u7387\u3002\r\n\r\n\u6240\u4ee5\u6b64\u5bf9\u8c61\u6c60\u53ef\u4ee5\u6c60\u5316\u4e00\u5207python\u5bf9\u8c61\uff0c\u4e0d\u4ec5\u662f\u662f\u6570\u636e\u5e93\u8fde\u63a5\u3002\r\n\r\n```python\r\nimport time\r\n\r\nimport decorator_libs\r\nimport paramiko\r\nimport nb_log\r\nfrom threadpool_executor_shrink_able import BoundedThreadPoolExecutor\r\n\r\nfrom universal_object_pool import AbstractObject, ObjectPool\r\n\r\n\"\"\"\r\n t = paramiko.Transport((self._host, self._port))\r\n        t.connect(username=self._username, password=self._password)\r\n        self.sftp = paramiko.SFTPClient.from_transport(t)\r\n\r\n        ssh = paramiko.SSHClient()\r\n        ssh.load_system_host_keys()\r\n        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n        ssh.connect(self._host, port=self._port, username=self._username, password=self._password, compress=True)\r\n        self.ssh = ssh\r\n\"\"\"\r\n\r\n\r\nclass ParamikoOperator(nb_log.LoggerMixin, nb_log.LoggerLevelSetterMixin, AbstractObject):\r\n    \"\"\"\r\n    \u8fd9\u4e2a\u662flinux\u64cd\u4f5c\u5305\u7684\u6c60\u5316\u3002\u4f8b\u5982\u6267\u884c\u7684shell\u547d\u4ee4\u8017\u65f6\u6bd4\u8f83\u957f\uff0c\u5982\u679c\u4e0d\u91c7\u7528\u6c60\uff0c\u90a3\u4e48\u4e00\u4e2a\u63a5\u4e00\u4e2a\u7684\u547d\u4ee4\u6267\u884c\u5c06\u4f1a\u5f88\u8017\u65f6\u3002\r\n    \u5982\u679c\u6bcf\u6b21\u4e34\u65f6\u521b\u5efa\u548c\u6467\u6bc1linux\u8fde\u63a5\uff0c\u4f1a\u5f88\u591a\u8017\u65f6\u548c\u8017cpu\u5f00\u9500\u3002\r\n    \"\"\"\r\n    def __init__(self, host, port, username, password):\r\n        # self.logger = nb_log.get_logger('ParamikoOperator')\r\n\r\n        t = paramiko.Transport((host, port))\r\n        t.connect(username=username, password=password)\r\n        self.sftp = paramiko.SFTPClient.from_transport(t)\r\n\r\n        ssh = paramiko.SSHClient()\r\n        # ssh.load_system_host_keys()\r\n        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n        ssh.connect(host, port=port, username=username, password=password, compress=True)  # \u5bc6\u7801\u65b9\u5f0f\r\n\r\n        # private = paramiko.RSAKey.from_private_key_file('C:/Users/Administrator/.ssh/id_rsa')  # \u79d8\u94a5\u65b9\u5f0f\r\n        # ssh.connect(host, port=port, username=username, pkey=private)\r\n        self.ssh = self.core_obj = ssh\r\n\r\n        self.ssh_session = self.ssh.get_transport().open_session()\r\n\r\n    def clean_up(self):\r\n        self.sftp.close()\r\n        self.ssh.close()\r\n\r\n    def before_back_to_queue(self, exc_type, exc_val, exc_tb):\r\n        pass\r\n\r\n    def exec_cmd(self, cmd):\r\n        # paramiko.channel.ChannelFile.readlines()\r\n        self.logger.debug('\u8981\u6267\u884c\u7684\u547d\u4ee4\u662f\uff1a ' + cmd)\r\n        stdin, stdout, stderr = self.ssh.exec_command(cmd)\r\n        stdout_str = stdout.read().decode()\r\n        stderr_str = stderr.read().decode()\r\n        if stdout_str != '':\r\n            self.logger.info('\u6267\u884c {} \u547d\u4ee4\u7684stdout\u662f -- > \\n{}'.format(cmd, stdout_str))\r\n        if stderr_str != '':\r\n            self.logger.error('\u6267\u884c {} \u547d\u4ee4\u7684stderr\u662f -- > \\n{}'.format(cmd, stderr_str))\r\n        return stdout_str, stderr_str\r\n\r\n\r\nif __name__ == '__main__':\r\n    paramiko_pool = ObjectPool(object_type=ParamikoOperator,\r\n                               object_init_kwargs=dict(host='192.168.6.130', port=22, username='ydf',\r\n                                                       password='372148', ),\r\n                               max_idle_seconds=120, object_pool_size=20)\r\n\r\n    ParamikoOperator(**dict(host='192.168.6.130', port=22, username='ydf', password='372148', ))\r\n\r\n\r\n    def test_paramiko(cmd):\r\n        with paramiko_pool.get() as paramiko_operator:  # type:ParamikoOperator\r\n            # pass\r\n            ret = paramiko_operator.exec_cmd(cmd)\r\n            print(ret[0])\r\n            print(ret[1])\r\n\r\n\r\n    thread_pool = BoundedThreadPoolExecutor(20)\r\n    with decorator_libs.TimerContextManager():\r\n        for x in range(20, 100):\r\n            thread_pool.submit(test_paramiko, 'date;sleep 20s;date')  # \u8fd9\u4e2a\u547d\u4ee4\u5355\u7ebf\u7a0bfor\u5faa\u73af\u987a\u5e8f\u6267\u884c\u6bcf\u6b21\u9700\u898120\u79d2\uff0c\u5982\u679c\u4e0d\u7528\u5bf9\u8c61\u6c60\u6267\u884c80\u6b21\u89811600\u79d2\r\n            # thread_pool.submit(test_update_multi_threads_use_one_conn, x)\r\n        thread_pool.shutdown()\r\n    time.sleep(10000)  # \u8fd9\u4e2a\u53ef\u4ee5\u6d4b\u8bd5\u9a8c\u8bc1\uff0c\u6b64\u5bf9\u8c61\u6c60\u4f1a\u81ea\u52a8\u6467\u6bc1\u8fde\u63a5\u5982\u679c\u95f2\u7f6e\u65f6\u95f4\u592a\u957f\uff0c\u4f1a\u81ea\u52a8\u6467\u6bc1\u5bf9\u8c61\r\n    \r\n\r\n```\r\n\r\n### 2.3 \u4e00\u822c\u6027\u4efb\u610fpython\u5bf9\u8c61\u7684\u6c60\u5316\r\n\r\n```python\r\nimport typing\r\nfrom universal_object_pool import ObjectPool, AbstractObject\r\nfrom threadpool_executor_shrink_able import BoundedThreadPoolExecutor\r\nimport threading\r\nimport time\r\n\r\n\"\"\"\r\n\u7f16\u7801\u4e2d\u6709\u65f6\u5019\u9700\u8981\u4f7f\u7528\u4e00\u79cd\u521b\u5efa\u4ee3\u4ef7\u5f88\u5927\u7684\u5bf9\u8c61\uff0c\u800c\u4e14\u8fd9\u4e2a\u5bf9\u8c61\u4e0d\u80fd\u88ab\u591a\u7ebf\u7a0b\u540c\u65f6\u8c03\u7528\u4ed6\u7684\u64cd\u4f5c\u65b9\u6cd5\uff0c\r\n\r\n\u6bd4\u5982mysql\u8fde\u63a5\u6c60\uff0csocket\u8fde\u63a5\u6c60\u3002\r\n\u5f88\u591a\u8fd9\u6837\u7684\u4f8b\u5b50\u4f8b\u5178\u578b\u5982mysql\u7684\u63d2\u5165\uff0c\u5982\u679c\u591a\u7ebf\u7a0b\u9ad8\u5e76\u53d1\u540c\u65f6\u64cd\u4f5c\u540c\u4e00\u4e2a\u5168\u5c40connection\u53bb\u63d2\u5165\uff0c\u5f88\u5feb\u5c31\u4f1a\u62a5\u9519\u4e86\u3002\r\n\u90a3\u4e48\u4f60\u53ef\u80fd\u4f1a\u4e3a\u4e86\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u7684\u65b9\u5f0f\u6709\u5982\u4e0b\uff1a\r\n\r\n1.\u4f60\u53ef\u80fd\u8fd9\u4e48\u60f3\uff0c\u64cd\u4f5cmysql\u7684\u90a3\u4e2a\u51fd\u6570\u91cc\u9762\u6bcf\u4e00\u6b21\u90fd\u4e34\u65f6\u521b\u5efamysql\u8fde\u63a5\uff0c\u51fd\u6570\u7684\u672b\u5c3e\u5173\u95edcoonection\uff0c\r\n  \u8fd9\u6837\u9891\u7e41\u521b\u5efa\u548c\u6467\u6bc1\u8fde\u63a5\uff0c\u65e0\u8bba\u662f\u670d\u52a1\u7aef\u8fd8\u662f\u5ba2\u6237\u7aef\u5f00\u9500cpu\u548cio\u9ad8\u51fa\u5f88\u591a\u3002\r\n\r\n2.\u6216\u8005\u4e0d\u4f7f\u7528\u65b9\u68481\uff0c\u4f60\u662f\u591a\u7ebf\u7a0b\u7684\u51fd\u6570\u91cc\u9762\u7528\u4e00\u4e2a\u5168\u5c40connection\uff0c\u4f46\u662f\u6bcf\u4e00\u4e2a\u64cd\u4f5cmysql\u7684\u5730\u65b9\u90fd\u52a0\u4e00\u4e2a\u7ebf\u7a0b\u9501\uff0c\r\n  \u4f7f\u5f97\u4e0d\u53ef\u80fd\u7ebf\u7a0b1\u548c\u7ebf\u7a0b2\u540c\u65f6\u53bb\u64cd\u4f5c\u8fd9\u4e2aconnction\u6267\u884c\u63d2\u5165\uff0c\u5982\u679c\u5047\u8bbe\u63d2\u5165\u8017\u65f61\u79d2\uff0c\u90a3\u4e48100\u7ebf\u7a0b\u63d2\u51651000\u6b21\u89811000\u79d2\u3002\r\n\r\n\u6b63\u786e\u7684\u505a\u6cd5\u662f\u4f7f\u7528mysql\u8fde\u63a5\u6c60\u5e93\u3002\u5982\u679c\u8bbe\u7f6e\u5f00\u542f\u7684\u8fde\u63a5\u6c60\u4e2d\u7684\u6570\u91cf\u662f\u5927\u4e8e100\uff0c100\u7ebf\u7a0b\u63d2\u51651000\u6b21\u53ea\u9700\u898110\u79d2\uff0c\u8282\u7701\u65f6\u95f4100\u500d\u3002\r\nmysql\u8fde\u63a5\u6c60\u5df2\u7ecf\u6709\u77e5\u540d\u7684\u8fde\u63a5\u6c60\u5305\u4e86\u3002\u5982\u679c\u6ca1\u6709\u5927\u4f6c\u7ed9\u6211\u4eec\u5f00\u53d1mysql\u8fde\u63a5\u6c60\u5e93\u6216\u8005\u4e00\u4e2a\u5c0f\u4f17\u7684\u9700\u6c42\u8fd8\u6ca1\u6709\u5927\u795e\u9488\u5bf9\u8fd9\u4e2a\u8017\u65f6\u5bf9\u8c61\u5f00\u53d1\u8fde\u63a5\u6c60\u3002\r\n\u90a3\u4e48\u53ef\u4ee5\u4f7f\u7528 ObjectPool \u5b9e\u73b0\u5bf9\u8c61\u6c60\uff0c\u8fde\u63a5\u6c60\u5c31\u662f\u5bf9\u8c61\u6c60\u7684\u4e00\u79cd\u5b50\u96c6\uff0cconnection\u5c31\u662fpymysql.Connection\u7c7b\u578b\u7684\u5bf9\u8c61\uff0c\u8fde\u63a5\u4e5f\u662f\u5bf9\u8c61\u3002\r\n\u8fd9\u662f\u4e07\u80fd\u5bf9\u8c61\u6c60\uff0c\u6240\u4ee5\u53ef\u4ee5\u5b9e\u73b0webdriver\u6d4f\u89c8\u5668\u6c60\u3002\u5bf9\u8c61\u5e76\u4e0d\u662f\u9700\u8981\u4e25\u683c\u5b9e\u5b9e\u5728\u5728\u7684\u5916\u90e8cocket\u6216\u8005\u6d4f\u89c8\u5668\u4ec0\u4e48\u7684\uff0c\u4e5f\u53ef\u4ee5\u662fpython\u8bed\u8a00\u7684\u4e00\u4e2a\u666e\u901a\u5bf9\u8c61\u3002\r\n\u53ea\u8981\u8fd9\u4e2a\u5bf9\u8c61\u521b\u5efa\u4ee3\u4ef7\u5927\uff0c\u5e76\u4e14\u5b83\u7684\u6838\u5fc3\u65b9\u6cd5\u662f\u975e\u7ebf\u7a0b\u5b89\u5168\u7684\uff0c\u5c31\u5f88\u9002\u5408\u4f7f\u7528\u5bf9\u8c61\u6c60\u6765\u4f7f\u7528\u5b83\u3002\r\n\r\n\"\"\"\r\n\r\n\"\"\"\r\n\u6b64\u6a21\u5757\u6f14\u793a\u4e00\u822c\u5e38\u89c4\u6027\u4efb\u610f\u5bf9\u8c61\u7684\u6c60\u5316\r\n\"\"\"\r\n\r\n\r\nclass Core:  # \u4e00\u822c\u5047\u8bbe\u8fd9\u662f\u4e2a\u4e09\u65b9\u5305\u5927\u795e\u5199\u7684\u5305\u91cc\u9762\u7684\u67d0\u4e2a\u91cd\u8981\u516c\u6709\u7c7b,\u4f60\u9700\u8981\u5199\u7684\u662f\u7528has a \u6a21\u5f0f\u5c01\u88c5\u4ed6\uff0c\u4f60\u5f53\u7136\u4e5f\u53ef\u4ee5\u4f7f\u7528is a\u6a21\u5f0f\u6765\u7ee7\u627f\u5b83\u5e76\u52a0\u4e0aclean_up before_back_to_queue \u65b9\u6cd5\u3002\r\n    def insert(self, x):\r\n        time.sleep(0.5)\r\n        print(f'\u63d2\u5165 {x}')\r\n\r\n    def close(self):\r\n        print('\u5173\u95ed\u8fde\u63a5')\r\n\r\n\r\nclass MockSpendTimeObject(AbstractObject):\r\n\r\n    def __init__(self, ):\r\n        time.sleep(0.1)  # \u6a21\u62df\u521b\u5efa\u5bf9\u8c61\u8017\u65f6\r\n\r\n        s = 0  # \u6a21\u62df\u521b\u5efa\u5bf9\u8c61\u8017\u8d39cpu\r\n        for j in range(10000 * 500):\r\n            s += j\r\n\r\n        self.conn = self.core_obj = Core()  # \u8fd9\u4e2a\u4f1a\u9020\u6210obj.xx  \u81ea\u52a8\u8c03\u7528 obj.core_obj.xx\uff0c\u5f88\u597d\u7528\u3002\r\n\r\n        self._lock = threading.Lock()\r\n\r\n    def do_sth(self, x):\r\n        with self._lock:\r\n            self.conn.insert(x)\r\n            print(f' {x} \u5047\u8bbe\u505a\u67d0\u4e8b\u540c\u4e00\u4e2aobject\u53ea\u80fd\u540c\u65f6\u88ab\u4e00\u4e2a\u7ebf\u7a0b\u8c03\u7528\u6b64\u65b9\u6cd5\uff0c\u662f\u6392\u4ed6\u7684')\r\n\r\n    def clean_up(self):\r\n        self.core_obj.close()\r\n\r\n    def before_back_to_queue(self, exc_type, exc_val, exc_tb):\r\n        pass\r\n\r\n\r\nif __name__ == '__main__':\r\n    pool = ObjectPool(object_type=MockSpendTimeObject, object_pool_size=40).set_log_level(10)\r\n\r\n\r\n    def use_object_pool_run(y):\r\n        \"\"\" \u7b2c1\u79cd \u4f7f\u7528\u5bf9\u8c61\u6c60\u662f\u6b63\u89e3\"\"\"\r\n        # with ObjectContext(pool) as mock_obj:\r\n        #     mock_obj.do_sth(y)\r\n        with pool.get() as mock_obj:  # type:typing.Union[MockSpendTimeObject,Core]\r\n            # mock_obj.insert(y)  # \u53ef\u4ee5\u76f4\u63a5\u4f7f\u7528core_obj\u7684\u65b9\u6cd5\r\n            mock_obj.do_sth(y)\r\n\r\n\r\n    def create_object_every_times_for_run(y):\r\n        \"\"\"\u7b2c2\u79cd \u591a\u7ebf\u7a0b\u51fd\u6570\u5185\u90e8\u6bcf\u6b21\u90fd\u91c7\u7528\u4e34\u65f6\u521b\u5efa\u5bf9\u8c61\uff0c\u521b\u5efa\u5bf9\u8c61\u4ee3\u4ef7\u5927\uff0c\u5bfc\u81f4\u603b\u8017\u65f6\u5f88\u957f\"\"\"\r\n        mock_obj = MockSpendTimeObject()\r\n        mock_obj.do_sth(y)\r\n\r\n\r\n    global_mock_obj = MockSpendTimeObject()\r\n    global_mock_obj.insert(6666)  # \u81ea\u52a8\u62e5\u6709self.core_object\u7684\u65b9\u6cd5\u3002\r\n\r\n\r\n    def use_globle_object_for_run(y):\r\n        \"\"\"\r\n        \u7b2c3\u79cd \uff0c\u591a\u7ebf\u7a0b\u4e2d\uff0c\u4f7f\u7528\u5168\u5c40\u552f\u4e00\u5bf9\u8c61\u3002\u5c11\u4e86\u521b\u5efa\u5bf9\u8c61\u7684\u65f6\u95f4\uff0c\u4f46\u662f\u64cd\u4f5c\u662f\u72ec\u5360\u65f6\u95f4\u6392\u4ed6\u7684\uff0c\u8fd9\u79cd\u901f\u5ea6\u662f\u6700\u5dee\u7684\u3002\r\n        \"\"\"\r\n        global_mock_obj.do_sth(y)\r\n\r\n\r\n    t1 = time.perf_counter()\r\n    threadpool = BoundedThreadPoolExecutor(50)\r\n\r\n    for i in range(1000):  # \u8fd9\u91cc\u968f\u7740\u51fd\u6570\u7684\u8c03\u7528\u6b21\u6570\u8d8a\u591a\uff0c\u5bf9\u8c61\u6c60\u4f18\u52bf\u8d8a\u660e\u663e\u3002\u5047\u8bbe\u662f\u8fd0\u884c10\u4e07\u6b21\uff0c\u4e09\u8005\u8017\u65f6\u5dee\u8ddd\u4f1a\u66f4\u5927\u3002\r\n        # \u8fd9\u91cc\u6f14\u793a\u4e09\u79cd\u8c03\u7528\uff0c1\u662f\u591a\u7ebf\u7a0b\u91cc\u7528\u4f7f\u7528\u5bf9\u8c61\u6c60 2\u662f\u4f7f\u7528\u591a\u7ebf\u7a0b\u51fd\u6570\u5185\u90e8\u6bcf\u6b21\u4e34\u65f6\u521b\u5efa\u5173\u95ed\u5bf9\u8c61 3\u662f\u591a\u7ebf\u7a0b\u51fd\u6570\u5185\u90e8\u4f7f\u7528\u5168\u5c40\u552f\u4e00\u5bf9\u8c61\u3002\r\n\r\n        threadpool.submit(use_object_pool_run, i)  # 6\u79d2\u5b8c\u6210\r\n        # threadpool.submit(create_object_every_times_for_run, i)  # 82\u79d2\u5b8c\u6210\r\n        # threadpool.submit(use_globle_object_for_run, i)  # \u8017\u65f6100\u79d2\r\n\r\n    threadpool.shutdown()\r\n    print(time.perf_counter() - t1)\r\n\r\n    time.sleep(100)\r\n    \r\n```\r\n",
    "bugtrack_url": null,
    "license": "BSD License",
    "summary": "commmon  universal_object_pool",
    "version": "1.2",
    "project_urls": null,
    "split_keywords": [
        "commmon",
        "",
        "universal_object_pool"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6f31602e7df35c9450bfbebbc5db808b964904fcf91c947c641ade436fc8b57d",
                "md5": "1c3ca24e37da8385c5fc26c7f701713c",
                "sha256": "b593193bff38c5fb851b7b88919ccc15a132e6d34c4540f947c11dc2a1470293"
            },
            "downloads": -1,
            "filename": "universal_object_pool-1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "1c3ca24e37da8385c5fc26c7f701713c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 25567,
            "upload_time": "2023-10-26T09:19:52",
            "upload_time_iso_8601": "2023-10-26T09:19:52.202394Z",
            "url": "https://files.pythonhosted.org/packages/6f/31/602e7df35c9450bfbebbc5db808b964904fcf91c947c641ade436fc8b57d/universal_object_pool-1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-26 09:19:52",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "universal-object-pool"
}
        
Elapsed time: 0.12729s