简体   繁体   English

如何减少Ruby / Sinatra应用程序中的Redis连接? 使用connection_pool?

[英]How to reduce Redis connections in a Ruby/Sinatra app? Use connection_pool?

I have a working Sinatra app that uses redis-namespace for its Redis connections. 我有一个可以正常工作的Sinatra应用程序,该应用程序使用redis-namespace进行Redis连接。 It works fine, but on Heroku it keeps running out of its 10 Redis connections, despite having very little traffic - they seem to stay open for ages and the app keeps opening new ones. 它运行正常,但在Heroku上,尽管流量很少,但仍然用尽了10个Redis连接-它们似乎保持打开状态很久,并且该应用程序还在不断打开新的连接。

So, there might be a better way to structure what I've got, so it doesn't keep opening new connections. 因此,可能会有更好的方法来构造我所拥有的内容,因此它不会一直打开新的连接。 Or maybe I can use connection_pool ... although I'm not sure how to use that with redis-namespace. 或者也许我可以使用connection_pool ...,尽管我不确定如何将它 redis-namespace一起使用。

The Sinatra front end ( myapp/frontend.rb ) is something like: 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

And the Redis-accessing Store classes are in myapp/store.rb : 访问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

The frontend stores data via the Store classes: registration_store.add(37) . 前端通过Store类存储数据: registration_store.add(37)

Am I doing something wrong that keeps opening new connections unnecessarily? 我做错了什么事,导致不必要地打开新连接? Or, how can I add connection_pool or similar? 或者,如何添加connection_pool或类似的内容?

I bumped into a similar problem and stumbled upon this question. 我碰到一个类似的问题,偶然发现了这个问题。 I think you should add redis.quit somewhere in your code. 我认为您应该在代码中的某处添加redis.quit Doing some manual testing monitoring connections with client list on the redis command line gives that the connection disappears on a quit. 通过在redis命令行上使用client list进行一些手动测试监视连接,可以使连接在退出时消失。 The object can still be used later and will open a new connection it the connection is closed. 该对象以后仍可以使用,并且在关闭连接后将打开一个新连接。 No need for pooling! 无需池! (At least when the load is low.... I guess you may end up with calls not getting a connection under higher loads.) (至少当负载较低时...。我想您可能最终会因呼叫在较高负载下无法建立连接而告终。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM