我试图在我的 websocket 中只有一个数据库连接,并将此信息返回给每个连接的客户端。有可能这样做吗?
有我当前的代码:
import asyncio
import aiopg
import websockets
import logging
import sys
import configparser
config = configparser.ConfigParser()
config.read('config/config.ini')
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger('websockets.server')
logger2 = logging.getLogger('asyncio')
logger2.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger2.addHandler(logging.StreamHandler())
async def listen(websocket, path):
async with aiopg.create_pool(config.get('default', 'connexion_bd'), maxsize=1, pool_recycle=0) as pool:
async with pool.acquire() as conn1:
async with conn1.cursor() as cur:
await cur.execute(config.get('default', 'pg_listen'))
while True:
msg = await conn1.notifies.get()
if msg.payload == 'finish':
return
else:
await websocket.send(msg.payload)
start_server = websockets.serve(listen, 'localhost', config.getint('default', 'port_websocket_server'))
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
目前,每次客户端监听我的 websocket 时,我的数据库中都会有一个新连接。每个客户端都会获得相同的内容,所以我不需要它们连接到数据库,只需要我的 websocket。
我尝试拆分我的代码(连接到另一个正在连接这个的 websocket),但我遇到了同样的问题。
任何提示将不胜感激。
谢谢