uWSGI的lazy-apps配置

默認情況下lazy-apps的配置是False,uWSGI在第一個進程中加載整個應用程序,并且在加載應用程序之后,它會多次執行fork()本身的操作。可以極大地減少應用程序的內存使用,但也可能招來很多麻煩,比如在存在并發的時候,SQLAlchemy會報錯,數據庫連接丟失啥的,主要就是這個SQLAlchemy實例在整個app中只創建了一個,看下不配置lazy-apps時的啟動代碼,各種模塊都只創建了一遍,然后才創建worker

......
*** Operational MODE: preforking ***
create app(inc) id:140369684626512
create db id:140369663155112 via <class 'flask_sqlalchemy.SQLAlchemy'>
app.api.models models imported
app.admin.models models imported
install trying app.api
app.api.views imported
install trying app.admin
app.admin.views imported
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x5594c979e200 pid: 21129 (default app)
mounting inc:app on /
WSGI app 1 (mountpoint='/') ready in 1 seconds on interpreter 0x5594c9e58770 pid: 21129
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 21129)
spawned uWSGI worker 1 (pid: 21130, cores: 1)
spawned uWSGI worker 2 (pid: 21131, cores: 1)
*** Stats server enabled on 127.0.0.1:3167 fd: 14 ***

再看看lazy-apps=true時的啟動代碼,先創建worker,然后各種模塊都分別加載了一遍,每個worker的環境是獨立的,這樣有并發時SQLAlchemy就不會報錯了

*** Operational MODE: preforking ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 20980)
spawned uWSGI worker 1 (pid: 20981, cores: 1)
spawned uWSGI worker 2 (pid: 20982, cores: 1)
*** Stats server enabled on 127.0.0.1:3167 fd: 11 ***
create app(inc) id:140375376512168
create db id:140375355653144 via <class 'flask_sqlalchemy.SQLAlchemy'>
create app(inc) id:140375376512168
create db id:140375355653144 via <class 'flask_sqlalchemy.SQLAlchemy'>
app.api.models models imported
app.api.models models imported
app.admin.models models imported
app.admin.models models imported
install trying app.api
install trying app.api
app.api.views imported
app.api.views imported
install trying app.admin
app.admin.views imported
install trying app.admin
app.admin.views imported
WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x560cda997240 pid: 20981 (default app)
mounting inc:app on /
WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x560cda997240 pid: 20982 (default app)
mounting inc:app on /
WSGI app 1 (mountpoint='/') ready in 0 seconds on interpreter 0x560cdb051570 pid: 20982
WSGI app 1 (mountpoint='/') ready in 0 seconds on interpreter 0x560cdb051570 pid: 20981

想想之前用gunicorn時沒發現有這種問題,然后又用gunicorn啟動了一下看看有什么不同,當然它沒有這個配置項,但它的啟動是和lazy-apps=true差不多的,每個worker都是獨立的環境,這樣雖然占內存,但模塊彼此獨立,不會再出現資源競爭報錯的情況了

參考

https://uwsgi-docs.readthedocs.io/en/latest/articles/TheArtOfGracefulReloading.html?highlight=lazy-apps#preforking-vs-lazy-apps-vs-lazy
https://docs.gunicorn.org/en/latest/settings.html#workers

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。