如何在FastApi中使用AsyncElasticsearch连接池?

发布于 2025-01-11 10:07:24 字数 1141 浏览 2 评论 0原文

我的代码的相关部分如下:

@app.on_event("startup")
async def startup():
    es = Translator()
    app.state.es_conn = es.connect()


@app.on_event('shutdown')
async def shutdown_event():
    es = Translator()
    await es.close(app.state.es_conn)


@app.post('/query')
async def query(req: Request):
    es = Translator()
    es.set_conn(req.app.state.es_conn)

    return await es.search()


from elasticsearch import AsyncElasticsearch, AsyncTransport

class Translator(object):
    def __init__(self):
        self.__es = None

    def connect(self):
        return AsyncElasticsearch(
            hosts='http://192.168.0.2:9200/',
            transport_class=AsyncTransport)

    def set_conn(self, conn):
        self.__es = conn

    async def close(self, conn):
        await conn.close()
        self.__es = None

    async def search(self):
        return await self.__es.search(index=index, body=body)

它运行在以下环境中:

  • PyPy 7.3.7
  • fastapi 0.73.0
  • Elasticsearch 7.10.1

我的问题是:

  1. 虽然代码可以正常工作,但如何检测它是否使用连接池?
  2. 异步时如何正确使用连接池?

有人可以帮助我吗?谢谢你!

The relevant parts of my code are as follows:

@app.on_event("startup")
async def startup():
    es = Translator()
    app.state.es_conn = es.connect()


@app.on_event('shutdown')
async def shutdown_event():
    es = Translator()
    await es.close(app.state.es_conn)


@app.post('/query')
async def query(req: Request):
    es = Translator()
    es.set_conn(req.app.state.es_conn)

    return await es.search()


from elasticsearch import AsyncElasticsearch, AsyncTransport

class Translator(object):
    def __init__(self):
        self.__es = None

    def connect(self):
        return AsyncElasticsearch(
            hosts='http://192.168.0.2:9200/',
            transport_class=AsyncTransport)

    def set_conn(self, conn):
        self.__es = conn

    async def close(self, conn):
        await conn.close()
        self.__es = None

    async def search(self):
        return await self.__es.search(index=index, body=body)

It runs in the following environment:

  • PyPy 7.3.7
  • fastapi 0.73.0
  • Elasticsearch 7.10.1

My question are:

  1. Although the code can work normally, how can I detect whether it uses connection pool?
  2. How to use connection pool correctly when asynchronous?

Can anyone help me? Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文