gpt4 book ai didi

ruby-on-rails - Redis 对于 Rails 生产 I18n 来说太慢了吗?

转载 作者:IT王子 更新时间:2023-10-29 05:55:24 24 4
gpt4 key购买 nike

我最近从默认的简单 I18n 后端切换到我的 I18n 的 Redis 后端。我这样做是为了让我们更容易处理翻译,但我发现每个页面的性能都会受到很大影响。

我在我的 MBP 上安装了 Rails 3.2 和 Redis 2.6.4 来运行一些基准测试来进行演示。我正在使用 hiredis-rb作为我的客户。

在运行两个不同的后端时,这是一个非常明显的区别。使用简单的后端,第一次调用会有短暂的延迟——我假设翻译正在加载到内存中——然后性能很好:

pry(main)> Benchmark.realtime { 500.times { I18n.t 'shared.slogan' } }
=> 0.143246
pry(main)> Benchmark.realtime { 500.times { I18n.t 'shared.slogan' } }
=> 0.00415
pry(main)> Benchmark.realtime { 500.times { I18n.t 'shared.slogan' } }
=> 0.004153
pry(main)> Benchmark.realtime { 500.times { I18n.t 'shared.slogan' } }
=> 0.004056

Redis 后端一直很慢:

pry(main)> Benchmark.realtime { 500.times { I18n.t 'shared.slogan' } }
=> 0.122448
pry(main)> Benchmark.realtime { 500.times { I18n.t 'shared.slogan' } }
=> 0.263564
pry(main)> Benchmark.realtime { 500.times { I18n.t 'shared.slogan' } }
=> 0.232637
pry(main)> Benchmark.realtime { 500.times { I18n.t 'shared.slogan' } }
=> 0.122304

对我来说,为什么这对 I18n 来说很慢......我在我的代码库中排队了几十个 I18n 调用。如果我能预先将它们分批处理,我的状态就会很好:

pry(main)> keys = $redis.keys[0..500]
pry(main)> Benchmark.realtime { $redis.mget keys }
=> 0.04264

但我真的没有看到一个干净的方法来使用任何现有的 I18n 后端来做到这一点。有人解决过这个问题吗?

编辑

我采纳了 Chris Heald 的建议并创建了一个带有内存的后端,一个简单的缓存清除。要点在这里:

https://gist.github.com/wheeyls/5650947

我会试用几天,然后把它变成 gem 。

更新

我的解决方案现在作为 gem 提供:

https://github.com/wheeyls/cached_key_value_store

我也写过关于这个问题的博客:

http://about.g2crowd.com/faster-i18nredis-on-rails/

最佳答案

网络流量总是比本地工作慢。您可能会考虑使用内存中的缓存,然后在每次请求时(甚至只是在很短的时间内)提取当前的本地化版本,以确定是否使缓存失效。看起来有一个 Memoization 模块(根据 the source here ),您可以将其混合到 I18n 接口(interface)中。然后,我们只需调整 #lookup 方法,使其每 5 分钟检查一次 Redis 以获取更新的语言环境版本,并确保在保存新翻译时增加语言环境版本。

这为您提供了所有翻译的内存缓存,因此查找速度非常快,同时让您能够即时更改翻译 - 您的翻译最多可能需要 5 分钟才能更新,但您不必进行任何明确的缓存清除。

如果您愿意,您可以使用 before_filter 让它对每个请求进行检查,而不是仅仅使用延迟 5 分钟过期,这意味着对 redis 的更多请求,但您不会这样做查看任何过时的翻译。

module I18n
module Backend
class CachedKeyValueStore < KeyValue
include Memoize

def store_translations(locale, data, options = {})
@store.incr "locale_version:#{locale}"
reset_memoizations!(locale)
super
end

def lookup(locale, key, scope = nil, options = {})
ensure_freshness(locale)
flat_key = I18n::Backend::Flatten.normalize_flat_keys(locale,
key, scope, options[:separator]).to_sym
flat_hash = memoized_lookup[locale.to_sym]
flat_hash.key?(flat_key) ? flat_hash[flat_key] : (flat_hash[flat_key] = super)
end

def ensure_freshness(locale)
@last_check ||= 0

if @last_check < 5.minutes.ago
@last_check = Time.now
current_version = @store.get "locale_version:#{locale}"
if @last_version != current_version
reset_memoizations! locale
@last_version = current_version
end
end
end
end
end
end

我只是通过阅读 I18n 源代码破解了这个,我根本没有测试过它,所以它可能需要一些工作,但我认为它很好地传达了这个想法。

关于ruby-on-rails - Redis 对于 Rails 生产 I18n 来说太慢了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16746077/

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