在 Ruby on Rails 中,哪些数据(如果有)跨 Web 请求持续存在? [英] What data (if any) persists across web-requests in Ruby on Rails?

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

问题描述

我决定在创建视图助手类时使用单例设计模式.这让我开始思考;单例实例能否跨请求存活?这引出了另一个问题,哪些变量(如果有)在网络请求中存在,并且会根据部署发生变化吗?(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 实例变量不是持久化的.我知道常量是持久的(或重新加载?).但我不知道类变量,类上的实例变量,特征类,......

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天全站免登陆