Ruby on Rails 架构:为很少更新的数据预生成视图
我正在创建一个应用程序,该应用程序每 X 分钟轮询一次多个传感器,并在数据库中添加带有时间戳的新读数。最新数据可通过网页查看。
目前,我已经通过两个单独的进程实现了这一点:
- Cron 作业与每当,轮询传感器并更新数据库,通过模型
- 视图(具有关联的控制器和模型)从数据库中提取最新数据并显示它。
由于数据每 X 分钟更新一次,我认为每次轮询传感器时将视图预先生成为静态 HTML 可能更有效。这样我就可以将数据库访问量减少许多数量级。
这听起来是个好主意吗?使用 Rails 预生成视图的最佳方法是什么?
I'm creating an application that polls a number of sensors every X minutes and adds the new readings, with a timestamp, in the database. The latest data can be viewed via webpage.
Currently, I have implemented this with two separate processes:
- Cron job with Whenever, to poll the sensors and update the db, via the Model
- View (with associated Controller and Model) to pull the latest data off the database and display it.
Since the data only gets updated every X minutes, I was thinking it's probably more effective to pre-generate the View as static HTML, every time the sensors are polled. That way I reduce database accesses by many orders of magnitude.
Does this sound like a good idea? What would be the best way to pre-generate the view with Rails?
您基本上是在描述缓存,Rails 已经为您完成了这些工作。如果计算的输出页面没有改变,那么Rails不会每次都重新做,它只是给你缓存的版本。这是自动的,除非您明确将其关闭,否则您不必考虑它。
您使用的任何网络服务器也可能会执行类似的操作。
但是,默认情况下,在
开发
环境中,缓存是关闭的,并且每次刷新页面时都会重新加载视图。因此,如果您担心缓存在开发过程中被关闭,因此在生产中也会被关闭,但事实并非如此。缓存在开发过程中被有意关闭,因此您可以修改应用程序并在浏览器中点击刷新以即时查看差异,而无需重新启动开发 Web 服务器(Webrick 或 mongrel 或您正在使用的任何内容) 。You're basically describing caching, which Rails already does for you. If the computed output page doesn't change, then Rails doesn't re-do it every time, it just gives you the cached version. This is automatic, and you don't have to think about it unless you've explicitly turned it off.
It's also possible that whatever web server you're using does something similar as well.
However, by default, in the
development
environment caching is turned off, and views are reloaded every time you refresh the page. So, if you're worried that caching is off in development, and therefore it will be off in production, that shouldn't be the case. Caching is turned off in development intentionally, so you can be modifying your app and hitting refresh in your browser to see the differences on the fly, without having to restart your development web server (Webrick, or mongrel, or whatever you're using).