[英]How to reduce Redis connections in a Ruby/Sinatra app? Use connection_pool?
我有一個可以正常工作的Sinatra應用程序,該應用程序使用redis-namespace進行Redis連接。 它運行正常,但在Heroku上,盡管流量很少,但仍然用盡了10個Redis連接-它們似乎保持打開狀態很久,並且該應用程序還在不斷打開新的連接。
因此,可能會有更好的方法來構造我所擁有的內容,因此它不會一直打開新的連接。 或者也許我可以使用connection_pool ...,盡管我不確定如何將它與 redis-namespace一起使用。
Sinatra前端( myapp/frontend.rb
)類似於:
require 'sinatra/base'
require 'myapp/store'
module MyApp
class Frontend < Sinatra::Base
registration_store = MyApp::Store::Registration.new
subscription_store = MyApp::Store::Subscription.new
get '/' do
...
end
...
end
end
訪問Redis的Store類位於myapp/store.rb
:
require 'redis'
require 'redis-namespace'
module MyApp
module Store
class RedisBase
attr_accessor :redis
def initialize
uri = URI.parse(ENV['REDISCLOUD_URL'])
redis = ::Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
@redis = ::Redis::Namespace.new(:myapp, :redis => redis)
end
class Registration < RedisBase
def add(user_id)
redis.sadd(:registrations, user_id)
end
...
end
class Subscription < RedisBase
...
end
end
end
end
前端通過Store類存儲數據: registration_store.add(37)
。
我做錯了什么事,導致不必要地打開新連接? 或者,如何添加connection_pool或類似的內容?
我碰到一個類似的問題,偶然發現了這個問題。 我認為您應該在代碼中的某處添加redis.quit
。 通過在redis命令行上使用client list
進行一些手動測試監視連接,可以使連接在退出時消失。 該對象以后仍可以使用,並且在關閉連接后將打開一個新連接。 無需池! (至少當負載較低時...。我想您可能最終會因呼叫在較高負載下無法建立連接而告終。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.