我正在开发与API通讯的网络应用。为了提高性能,我尝试使用Faraday实现HTTP缓存。
首先,我尝试了标准的:memory_cache
:
@conn = Faraday.new(url: URL) do |builder|
builder.use :http_cache, store: Rails.cache, logger: ActiveSupport::Logger.new(STDOUT)
builder.adapter Faraday.default_adapter
end
development.rb:
...
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
...
tmp/caching-dev.txt
到位,因此启用了缓存。
但是对于每个API请求,我都得到了:
HTTP Cache: [GET /parks] miss, uncacheable
对于使响应不可缓存的原因,没有任何解释。至少我找不到它。
然后我尝试切换到自定义内存缓存:
class CustomCacheStore
attr_accessor :store_hash
def initialize
@store_hash = Hash.new
end
def write(key, value)
end
def read(key)
end
def fetch(key)
raise 'No block provided' unless block_given?
result = read(key)
if result.nil?
result = yield
write(key, result)
end
result
end
end
法拉第配置:
custom_store = CustomCacheStore.new
@conn = Faraday.new(url: URL) do |builder|
builder.use FaradayMiddleware::Caching, store: custom_store, logger: ActiveSupport::Logger.new(STDOUT)
builder.adapter Faraday.default_adapter
end
仍然相同:
HTTP Cache: [GET /parks] miss, uncacheable
该API也是用RoR编写的,并在具有以下配置的nginx服务器上运行:
upstream puma { server unix:///{...}; }
server { listen 8000 default_server deferred;
root {...}
access_log {...}
error_log {...}
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public; }
try_files $uri/index.html $uri @puma; location @puma {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://puma; }
error_page 500 502 503 504 /500.html;
client_max_body_size 1500M;
keepalive_timeout 10;
}
Rails 5.1.6