gpt4 book ai didi

ruby-on-rails - rails 中的 caches_page,json 格式

转载 作者:太空宇宙 更新时间:2023-11-03 16:06:24 25 4
gpt4 key购买 nike

我有一个设置为缓存 json 调用的应用程序。我尝试了各种代码语法,它似乎只有在我有以下内容时才能正确缓存:

    caches_page :index, :gzip => true
cache_sweeper :institutes_sweeper

respond_to :json, :js

def index
@institutes = Institute.select([:id, :name]).all
render :json => { :institutes => @institutes }
end

现在,当它被命中时,它会呈现一个 html 文件并且缓存会按预期工作。 Rails 堆栈不会受到影响。

如果我抛出一个格式 block 并让渲染响应 json,缓存将创建文件;但是,下次它会创建另一个文件并忽略已经存在的文件。

是否必须对 apache 进行不同的配置才能按预期工作?

另外,我想使用 public/cache/作为存放缓存的目录。我的 Rails 配置正确;但是,我想知道如何配置 apache 来提供这些缓存文件(上面的相同问题发生在创建文件但未提供文件的地方)。

感谢您的帮助!

最佳答案

只是想在这里留下我的问题的解决方案。

Apache 需要被告知缓存文件所在的位置。它仅存储在公共(public)区域时起作用的原因是因为这是默认情况下 apache 的行为方式。将以下配置添加到您定义虚拟主机的任何位置

RailsAllowModRewrite On
RewriteEngine On

RewriteCond %{THE_REQUEST} ^(GET|HEAD)
RewriteCond %{REQUEST_URI} ^/([^.]+)$
RewriteCond %{DOCUMENT_ROOT}/cache/%1.json -f
RewriteRule ^/[^.]+$ /cache/%1.json [QSA,L]

RewriteCond %{THE_REQUEST} ^(GET|HEAD)
RewriteCond %{DOCUMENT_ROOT}/cache/index.json -f
RewriteRule ^/$ /cache/index.json [QSA,L]

RewriteCond %{THE_REQUEST} ^(GET|HEAD)
RewriteCond %{REQUEST_URI} ^/([^.]+)$
RewriteCond %{DOCUMENT_ROOT}/cache/%1.html -f
RewriteRule ^/[^.]+$ /cache/%1.html [QSA,L]

RewriteCond %{THE_REQUEST} ^(GET|HEAD)
RewriteCond %{DOCUMENT_ROOT}/cache/index.html -f
RewriteRule ^/$ /cache/index.html [QSA,L]

现在,解决 json 呈现 html 的问题,我发现这是因为我在应用程序 Controller 中的调用在实际函数执行之前执行。如果我在这些函数上使用 skip_before_filter,我就更近了一步。

我还发现将响应包装在格式 block 中会更好。

respond_to do |format| 
format.json { json: { institutes: @institutes } }
end

这将导致 json 被缓存,服务器配置将导致它被正确提供。

我相信对于那些使用 Nginx 的人来说,应该使用以下配置(虽然不是 100% 确定)

    if (-f $request_filename/index.html) {
rewrite (.*) $1/cache/index.html break;
}

if (-f $request_filename/index.json) {
rewrite (.*) $1/cache/index.json break;
}

如果有人对上面的代码有任何反馈,我很乐意听到。谢谢!

关于ruby-on-rails - rails 中的 caches_page,json 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12868352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com