Ruby on rails 在Rails和Sinatra之间通过memcached共享数据时,如何修复Sinatra不处理ActiveSupport的问题

Ruby on rails 在Rails和Sinatra之间通过memcached共享数据时,如何修复Sinatra不处理ActiveSupport的问题,ruby-on-rails,sinatra,memcached,Ruby On Rails,Sinatra,Memcached,有没有办法让Sinatra透明地正确处理Rails编写的缓存数据,例如隐式处理Rails存储数据时使用的ActiveSupport类 Heroku托管的Rails 4应用程序和Sinatra应用程序使用共享的Memcachier存储来共享某些短暂的数据 如果在Sinatra上创建了一个键/值,则一切正常: # on Sinatra: session.cache.set("foo", "from sinatra", 100) 将设置Sinatra应用程序或

有没有办法让Sinatra透明地正确处理Rails编写的缓存数据,例如隐式处理Rails存储数据时使用的ActiveSupport类

Heroku托管的Rails 4应用程序和Sinatra应用程序使用共享的Memcachier存储来共享某些短暂的数据

如果在Sinatra上创建了一个键/值,则一切正常:

# on Sinatra:
session.cache.set("foo", "from sinatra", 100)
将设置Sinatra应用程序或Rails应用程序都可以读取的键,并且任何一个应用程序都将在100秒内过期后自动读取
nil
并且Rails和Sinatra都将数据值的类别报告为字符串。

但是,如果数据是由Rails应用程序设置的:

# on Rails:
Rails.cache.write("foo", "from rails", expires_in: 100)
Rails应用程序
read
返回一个字符串(如预期的那样),但Sinatra应用程序
get
返回类ActiveSupport::Cache::Entry

# on Sinatra
d = settings.cache.get("foo")
=> #<ActiveSupport::Cache::Entry:0x7f7ea70 @value="from rails", @created_at=1598330468.8312092, @expires_in=100.0>
目前,memcache存储按照Heroku在线文档进行配置:

require 'dalli'
set :cache, Dalli::Client.new(
 (ENV["MEMCACHIER_SERVERS"] || "").split(","),
 {:username => ENV["MEMCACHIER_USERNAME"],
  :password => ENV["MEMCACHIER_PASSWORD"],
  :failover => true, # default is true
  :socket_timeout => 1.5, # default is 0.5
  :socket_failure_delay => 0.2, # default is 0.01
  :down_retry_delay => 60 # default is 60
 })
编辑-根据已接受的答案解决Sinatra/Rails数据互操作性的关键是显式配置缓存存储以使用ActiveSupport,后者仍然自动使用Dalli gem来管理与memcachier服务的连接

set :cache, ActiveSupport::Cache::MemCacheStore.new(
... # init parameters
)}
这也意味着使用
settings.cache.read/write
方法(与使用Dalli::Client.new进行配置时使用的
settings.cache.get/set
方法相比)

附加编辑:


在模型内使用缓存时,无法直接访问settings.cache,需要使用Sinatra::Application.settings.cache.read()

cache_store = ActiveSupport::Cache::MemCacheStore.new('localhost')

# For writing the keys:
cache_store.write("foo", "from rails", expires_in: 100)

# For reading the keys
cache_store.read("foo")

编辑

似乎您正在使用gem,您也可以使用
DalliStore
而不是
MemCacheStore
,如下所示:

cache_store = ActiveSupport::Cache::DalliStore.new('localhost')
# For writing the keys:
cache_store.write("foo", "from rails", expires_in: 100)
    
# For reading the keys
cache_store.read("foo")

cache_store = ActiveSupport::Cache::DalliStore.new('localhost')
# For writing the keys:
cache_store.write("foo", "from rails", expires_in: 100)
    
# For reading the keys
cache_store.read("foo")