Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist mysql connection (mysql2 gem) with Ruby (no RoR)

Tags:

ruby

mysql2

rack

I have a very simple web service using Rack, without Rails that I will contact MySQL on every valid connection. I want to persist the connection (for example in the constructor), so that on every request I reuse it. Lets say something like this:

  class Service

    def initialize(dbhost, dbport, dbname, dbuser, dbpass)
      @client = Mysql2::Client.new(
          :host => dbhost, 
          :port => dbport, 
          :database => dbname,
          :username => dbuser, 
          :password => dbpass)
    end

    def call(env)
       # some logic that will call:
       results = _query(sql)
    end

    def _query(sql)
      results = @client.query(sql)
    end

  end

  Rack::Handler::Mongrel.run Service.new(DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASS), :Port => 8123  

With the code above, the service will obtain a MySQL connection and on every request it will do a query. But how do I make sure that if the connection drops, the _query method will reconnect?

like image 381
ddinchev Avatar asked Jan 29 '26 01:01

ddinchev


1 Answers

Well, :reconnect => true seems to ensure that the connection is persisted.

  @client = Mysql2::Client.new(
      :host => dbhost, 
      :port => dbport, 
      :database => dbname,
      :username => dbuser, 
      :password => dbpass,
      :reconnect => true
      )
like image 170
ddinchev Avatar answered Jan 30 '26 20:01

ddinchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!