我尝试使用SQL查询缓存大量数据(100 000),但缓存无效(写入缓存需要大约30秒,读取的时间相同)它)我做错了什么?我的配置变量已经设置为true
query = "SELECT inscriptions.`id`, banners.`id`, banners.`name`, inscriptions.`registered_at`,
inscriptions.`synched_at`, inscriptions.`state`
FROM inscriptions
JOIN firm_offices
ON inscriptions.`firm_office_1_id` = firm_offices.`id`
JOIN firms
ON firm_offices.`firm_id` = firms.`id`
JOIN banners
ON firms.`banner_id` = banners.`id`
GROUP BY inscriptions.`id`"
result = ActiveRecord::Base.connection.execute(query)
Rails.cache.fetch 'huge-array' do
data = []
result.each do |r|
data.push({ :id => r[0],
:banner_id => r[1],
:banner_name => r[2],
:registered_at => r[3],
:synched_at => r[4],
:state => r[5]})
end
data
end
@data = Rails.cache.read("huge-array")
答案 0 :(得分:1)
将它全部移到fetch
区块内:
@data ||= Rails.cache.fetch 'huge-array' do
query = "SELECT inscriptions.`id`, banners.`id`, banners.`name`, inscriptions.`registered_at`, inscriptions.`synched_at`, inscriptions.`state`
FROM inscriptions
JOIN firm_offices
ON inscriptions.`firm_office_1_id` = firm_offices.`id`
JOIN firms
ON firm_offices.`firm_id` = firms.`id`
JOIN banners
ON firms.`banner_id` = banners.`id`
GROUP BY inscriptions.`id`"
result = ActiveRecord::Base.connection.execute(query)
data = []
result.each do |r|
data.push({ :id => r[0],
:banner_id => r[1],
:banner_name => r[2],
:registered_at => r[3],
:synched_at => r[4],
:state => r[5]})
end
data
end
注意:
execute(query)
)。to_sql
,如果结果更有效。答案 1 :(得分:0)
每次调用此函数时都无需运行查询和获取块。尝试像
这样的东西@data = Rails.cache.read("huge-array")
if @data.empty?
result = ActiveRecord::Base.connection.execute(query)
@data = []
result.each do |r|
@data.push({ :id => r[0],
:banner_id => r[1],
:banner_name => r[2],
:registered_at => r[3],
:synched_at => r[4],
:state => r[5]})
end
Rails.cache.write("huge-array", @data)
end
return @data
这样,如果缓存中不存在数据,您只需要进行昂贵的查询+数组创建。