简体   繁体   English

在 gunicorn 工人之间共享内存中的动态数据

[英]Share dynamic data in memory between gunicorn workers

I have a web app written in Django/Celery/Postgres/Gunicorn/Nginx.我有一个用 Django/Celery/Postgres/Gunicorn/Nginx 编写的网络应用程序。

The app allows performing scientific simulations to the user.该应用程序允许对用户进行科学模拟。 These simulations can take from 5 seconds to 5 minutes.这些模拟可能需要 5 秒到 5 分钟。 Regular requests and quick simulations are done with the standard blocking paradigm while long simulations are run in the background (some are even submitted to several AWS Lambda instances in parallel) by celery and then the client is updated by a WebSocket.常规请求和快速模拟使用标准阻塞范例完成,而长时间模拟在后台运行(有些甚至并行提交到多个 AWS Lambda 实例)由 celery 完成,然后客户端由 WebSocket 更新。

When a client logs in and opens one of his projects, a Simulation object is initialized and stored in a dict as {user:Simulation}.当客户登录并打开他的一个项目时,模拟对象被初始化并作为 {user:Simulation} 存储在字典中。 Initializing this Simulation object can take about 10 seconds so it is only done at the beginning.初始化这个 Simulation 对象大约需要 10 秒,所以它只在开始时完成。 Every time the user interacts with his simulation on the client side, a particular view queries the Simulation object to the global dict and applies any changes, retrieves data, saves the simulation, runs the simulation, etc.每次用户在客户端与他的模拟交互时,特定视图都会将 Simulation 对象查询到全局 dict 并应用任何更改、检索数据、保存模拟、运行模拟等。

The problem with this approach is that it only works with 1 gunicorn worker since additional workers do not have access to the Simulation objects inside the global dict.这种方法的问题在于它只适用于 1 个 gunicorn 工人,因为其他工人无权访问全局 dict 内的模拟对象。 Moreover, it is not possible to pre-load the objects since they are constantly changed by the user.此外,由于用户不断更改对象,因此无法预加载对象。

What is the best approach to work with such global dynamic object, that is too expensive to be re-initialized with every request ?使用这种全局动态对象的最佳方法是什么,因为每个请求都太昂贵而无法重新初始化?

I think you want a memcache here:我想你想要一个内存缓存:

https://docs.djangoproject.com/en/2.1/topics/cache/#memcached https://docs.djangoproject.com/en/2.1/topics/cache/#memcached

The basic interface is set(key, value, timeout) and get(key):基本接口是set(key, value, timeout)和get(key):

>>> from django.core.cache import cache
>>> cache.set('my_key', 'hello, world!', 30)
>>> cache.get('my_key')
'hello, world!'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM