2

我完全迷失了我的 aiohttp 服务器的部署选项;有多种方法可以在生产中移动服务,我无法选择正确的一种:

  1. systemd script/supervisord + api hour 缺点:我不明白 api hour 是如何工作的,好像啊控制了服务器的守护进程协程,但是我的服务器的 coro 运行(低级别 aiohttp 服务器/连接处理程序)在 asyncio.gather 函数中其他 coro(主管/状态管理员的类永远运行方法),使用 api 小时处理第二个协程可能会出现问题
  2. gunicorn 和 1 一样
  3. nginx + unix socket +systemd 脚本 缺点:看起来很难部署和支持;
  4. systemd 脚本下的纯 aiohttp 服务器:缺点:处理 pid 文件,性能低下(?)我很乐意看到任何关于我的问题的想法,谢谢!

我的运行功能如下所示:

def run():
    startTime = time.time()
    logging.basicConfig(level=logging.INFO, format="%(asctime)s [ %(levelname)s ]: %(message)s")
    cfg = ConfigStore("server_config.cfg")
    loop = asyncio.get_event_loop()
    logging.info("Starting server")
    db = DBProxyLayer.fabric(cfg("dbCredentials"))
    logging.info("DBLayer initialized {}".format(db))
    try:
        supervisor = QPSServerSupervisor(loop=loop, db=db, config=cfg)
        srvCoro = loop.create_server(lambda: QPSServer(
                    supervisor=supervisor, debug=False, keep_alive_on=False, loop=loop),
                    host=cfg("command_host"), port=cfg("command_port"))
        loop.run_until_complete(asyncio.gather(*(srvCoro, supervisor.startToServe())))
    except Exception as e:
        logging.critical("Server start failure {}\n{}".format(e, traceback.print_exc()))
        sys.exit(-1)
    else:
        logging.info("Server started for {0:.2f} seconds".format(time.time()-startTime))
    try:
        loop.run_forever()
    except Exception as e:
        logging.info(e)
        loop.close()
        sys.exit(-1)
4

1 回答 1

0

loop.create_server可以使用sock=关键字在预先存在的套接字上激活。我的方法是

try:
    import systemd.daemon
except ImportError:
    def listeners(hosts, port):
        for host in hosts:
            _log.info("Starting server at %s on port %d", host, port)
            yield dict(host=host, port=port)
else:
    def listeners(hosts, port):
        daemon_fds = list(
            fd
            for fd in systemd.daemon.listen_fds()
            if systemd.daemon.is_socket_inet(
                fd,
                type=socket.SOCK_STREAM,
                listening=1,
            )
        )

        if len(daemon_fds) == 0:
            for host in hosts:
                _log.info("Starting server at %s on port %d", host, port)
                yield dict(host=host, port=port)
        else:
            _log.info("Starting server from systemd-provided file descriptors %r", daemon_fds)
            yield from (
                dict(sock=fd)
                for fd in daemon_fds
            )

然后在 中run,我遍历yielded dicts:

coros = []
for listener_args in listeners(hosts, port):
    coro = loop.create_server(factory, ssl=ssl_context, **listener_args)
    coros.append(coro)
coros.append(supervisor.startToServe())
results = loop.run_until_complete(asyncio.gather(*coros))
于 2016-12-03T17:18:33.420 回答