這聽起來像一個偉大的論據使用的memcached或Redis的。你需要一個集中的地方,這些值可以存活,所有的應用服務器池都可以訪問這些值。你的用例主要是偶爾寫入來更新值。
我會構建一個貨幣助手,它可以根據請求從memcached/redis延遲加載一次,然後爲該請求中的任何值計算保存貨幣匯率數據。
我不知道你的問題域,但是讓我們假設你試圖爲系統中的不同用戶提供本地貨幣定價,並且不同用戶的利率是不同的(例如:折扣等)。
class CurrencyHelper
attr_reader :currency_rates
def initialize(user_id)
@currency_rates = load_or_generate_exchange_rates
end
def load_or_generate_exchange_rates
key = "/currency/rates/#{user_id}"
REDIS.get(key) || begin
rates = generate_exchange_rates
REDIS.put(key, rates)
rates
end
end
def convert_from_usd_to(amount_usd, currency)
round_money(usd * currency_rates[currency])
end
end
在控制器代碼:
def currency_helper
@currency_helper ||= CurrencyHelper.new(current_user.id)
end
def show
localized_price = currency_helper.convert_from_usd_to(price_usd, params[:country_code])
end
爲什麼會是40個分貝電話?在這個典型的例子中爲 – KingCronus
:因爲我需要執行40個貨幣轉換。所以如果兩次使用同一種貨幣,其中一些可能會被緩存,但我不能依賴這個假設。 我可能會一勞永逸地加載所有必要的匯率,但這根本不實際...... – Pierre