SQLAlchemy:发送响应后写入数据库
我有一个简单的服务,大约执行以下操作:
- HTTP 客户端连接到服务器
- 服务器将客户端的 sessionID 和时间戳写入数据库,并且在大多数情况下只返回一个空响应
(当它确实做实际工作并返回实际数据与这个问题无关)
为了尽快返回此响应,我想将信息写入请求处理程序主体中的memcache(因为memcache速度很快) ,并生成一个单独的线程,其中另一个使用 SQLAlchemy 的函数将其写入持久存储。这样,我将能够在写入内存缓存并生成线程后立即返回,并且请求处理程序不必等到 SQLAlchemy 将信息保存到数据库。
这有道理吗?如果是,我应该如何实施?
I have a simple service that does approximately the following:
- An HTTP client connects to the server
- The server writes the sessionID of the client and the timestamp to the database, and in most cases just returns an empty response
(The cases when it does do real work and return actual data are irrelevant to this question)
In order to return this response as soon as possible, I'd like to write the info to memcache in the request handler's body (because memcache is fast), and to spawn a separate thread where another function using SQLAlchemy will write it to the persistent storage. This way, I'll be able to return immediately after writing to memcache and spawning a thread, and the request handler will not have to wait until SQLAlchemy saves the info to the database.
Does this make sense? If yes, how should I implement it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Celery 分布式任务队列之类的东西将处理卸载到其他计算机。它确实需要设置单独的基础设施,但允许将任务从 Web 请求移交到后台进行处理,同时可以立即返回对请求的 HTTP 响应。
You could use something like the Celery distributed task queue to offload processing to other machines. It does require setup of a separate infrastructure, but will allow for tasks to be handed off from web requests for processing in the background, while the HTTP repsonse to the request can be returned immediately.