在Ruby on Rails中的Web请求中有什么数据(如果有)? [英] What data (if any) persists across web-requests in Ruby on Rails?

查看:176
本文介绍了在Ruby on Rails中的Web请求中有什么数据(如果有)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建视图助手类时,我决定使用 singleton 设计模式。这让我想到了;单元实例会否在请求中存活?这导致另一个问题,哪些变量(如果有)存在跨网络请求,并且这会根据部署而改变吗? (Fastcgi,Mongrel,Passenger,...)

I decided to use the singleton design pattern while creating a view helper class. This got me thinking; will the singleton instance survive across requests? This led to another question, Which variables (if any) survive across web requests and does that change depending on deployment? (Fastcgi, Mongrel, Passenger, ...)

我知道Controller实例变量没有持久化。我知道常量是持久的(或重新加载?)。但我不知道类变量,类的实例变量,Eigenclasses,...

I know that Controller instance variables aren't persisted. I know Constants are persisted (or reloaded?). But I don't know about class variables, instance variables on a class, Eigenclasses, ...

推荐答案

没有。每个请求被视为独立事件,除了存储在用户会话和任何外部数据库,高速缓存或文件存储中的内容之外,不传输任何状态信息。最好是在设计应用程序时考虑到这一点,并且不要指望因为您设置它们而导致持续存在。

The simple answer is none. Each request is treated as an independent event and no state information is carried over apart from what is stored in the user session and any external databases, caches, or file stores. It is best that you design your application with this in mind and not expect things to persist just because you've set them.

更复杂的故事是,有些事情坚持。例如,您可以在控制器上创建一个类变量,这将从一个请求到下一个请求,如你所期望的。捕获是,这仅适用于该控制器的单个实例,如包含在该进程内,并且不适用于由其他进程服务的请求。如果你需要缓存,使用Rails.cache基础设施,避免自己的黑客。

The more complicated story is that some things do persist. For example, you can create a class variable on a controller and this will be carried from one request to the next as you might expect. The catch is that this only applies to the singular instance of that controller, as contained within that process, and will not apply to requests served by other processes. If you need caching, make use of the Rails.cache infrastructure and avoid hacking in your own.

典型的生产环境是一个复杂,不断变化的事情,被不断地创建和销毁,并且没有办法预先确定哪个进程最终将最终服务于特定请求。由于许多部署不仅涉及单个机器上的多个进程,而且涉及多个机器,因此实际上没有实际的方法来创建应用程序范围的单例对象。

A typical production environment is a complicated, ever-changing thing, where processes are created and destroyed constantly and there is no way to determine in advance which process will ultimately end up serving a particular request. As many deployments involve not only multiple processes on a single machine, but multiple machines, there really is no practical way to create application-wide singleton objects.

可以做的是在缓存引擎之上构建一个层,其中单例对象仅仅是从缓存中提取和写入的函数的包装器。这将为您提供单个对象的外观,同时保持进程间的一致性。

The best thing you can do is build a layer on top of the caching engine where your singleton object is merely a wrapper to functions that fetch and write from the cache. This gives you the appearance of a singleton object while maintaining inter-process consistency.

这篇关于在Ruby on Rails中的Web请求中有什么数据(如果有)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆