简体   繁体   English

HTTP请求之间具有持久状态的模型

[英]Models with persistent state between HTTP requests

I want to create a web application with a model that persists between HTTP requests. 我想创建一个Web应用程序,其模型在HTTP请求之间保持不变。 From what I understand languages like PHP treat each HTTP request as a brand new connection except for some global variables like SESSION; 根据我的理解,像PHP这样的语言将每个HTTP请求视为一个全新的连接,除了一些全局变量,如SESSION; so each time the user changes pages all my PHP classes are loaded into memory again (and each AJAX request does this too) - requiring me to build from the database each time. 因此,每次用户更改页面时,我的所有PHP类都会再次加载到内存中(并且每个AJAX请求也会这样做) - 每次都需要我从数据库构建。

Am I mistaken or am I trying to make a circle fit in a square? 我错了还是我试图在一个正方形中形成圆圈? Memcached seems to be a good solution for keeping my model in memory between page requests but it still needs to load the cache. Memcached似乎是一个很好的解决方案,可以将我的模型保存在页面请求之间的内存中,但它仍然需要加载缓存。 PHP CLI seemed promising but after looking into it more it seemed like it would be more trouble than it was worth. PHP CLI看起来很有希望,但在进行了更多研究之后,它似乎比它的价值更麻烦。 Any suggestions? 有什么建议?

You should avoid requiring a persistent state in your web application; 您应该避免在Web应用程序中要求持久状态; HTTP is stateless and you need to design your business logic around that. HTTP是无状态的,您需要围绕它设计业务逻辑。 Also, PHP isn't very memory-leak safe since it isn't meant to act as a daemon or run for extended periods. 此外,PHP不是非常安全的内存泄漏,因为它不是作为守护进程或长时间运行。 You shouldn't be maintaining a database of information in PHP variables either. 您也不应该在PHP变量中维护信息数据库。 You can cache expensive query results in memcache and retrieve them with very little latency. 您可以在memcache中缓存昂贵的查询结果,并以非常小的延迟检索它们。

You can serialize your model, store it in a session (or memcache), and deserialize it on the next request in order to keep relevant variables within scope between requests. 您可以序列化模型,将其存储在会话(或内存缓存)中,并在下一个请求中对其进行反序列化,以便将相关变量保持在请求之间的范围内。 If you share a bit more about the specifics of your application, perhaps we can help you figure out the best way to handle this. 如果您分享有关应用程序细节的更多信息,也许我们可以帮助您找出处理此问题的最佳方法。

I do agree that one should try to avoid sharing states between requests. 我同意应该尽量避免在请求之间共享状态。 But in rare cases, such as to implement a simple message queue over HTTP, It's desirable to have this feature in hand. 但在极少数情况下,例如通过HTTP实现简单的消息队列,需要手头有这个功能。

For php, one could use IPC via the php_shmop extension. 对于php,可以通过php_shmop扩展使用IPC。

For nodejs, I found this 对于nodejs,我发现了这一点

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

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