2013-08-07 50 views
4

我知道这个问题已被问了几次,但我仍然不确定使用线程的scoped_session。基本上,我有一个应用程序与10个工作线程。我有一个连接池大小为11的Engine。每个线程都有它自己的会话,并且不需要在线程的会话中共享信息(如果可以,那很好,但我已经创建了一个解决方法)。最后,我在复杂SQL语句的主线程中使用SQLAlchemy Core,这就是为什么我在连接池中有11个线程。线程和SQLAlchemy会话

我使用MySQL和我的pool_recycle设置为3600。我不断收到错误:

(OperationalError) (2013, 'Lost connection to MySQL server during query')

当我刚一个工作线程,即使没有任何pool_recycle集这从来没有发生过。我对MySQL和SQLAlchemy有一个非常基本的理解,所以我不确定我的问题是源于我使用SQLAlchemy还是MySQL(或者上面没有提到)。

这里是我的设置:

common = Common() 
class Common(object): 
    def __init__(self): 
    ... 
     self.engine = create_engine(
      '%(type)s://%(username)s:%(password)[email protected]%(endpoint)s:%(port)s/%(name)s?charset=utf8' % { 
       'type': config.get('db_type'), 
       'username': 'foo', 
       'password': 'bar', 
       'endpoint': config.get('db_endpoint'), 
       'port': str(config.get('db_port')), 
       'name': config.get('db_name'), 
      }, 
     encoding='utf-8', 
     pool_size=config.get('num_workers') + 1, 
     pool_recycle=3600, 
    ) 
    self.session = sessionmaker(bind=self.engine) 

每个工人呼吁self.session = common.session()和使用整个会话。

+0

[查询过程中丢失连接到MySQL服务器]的可能重复(http://stackoverflow.com/questions/1884859/lost-connection-to-mysql-server-during-query) – SingleNegationElimination

+0

在哪里这里使用'scoped_session'吗?也许尝试:'self.session = scoped_session(sessionmaker(bind = self.engine))'然后做:'self.session(); self.session.query ....; self.session.remove()' – jaor

回答