Skip to content

Instantly share code, notes, and snippets.

@gregorymostizky
Created February 1, 2011 15:06
Show Gist options
  • Save gregorymostizky/805976 to your computer and use it in GitHub Desktop.
Save gregorymostizky/805976 to your computer and use it in GitHub Desktop.
Simple connection pool for evented mysql2
require 'mysql2'
require 'mysql2/em'
class MysqlConnectionPool
def initialize(conf)
@pool_size = conf[:size] || 10
@connections = []
@query_queue = EM::Queue.new
start_queue conf
end
def queue_worker_loop
proc{ |connection|
@query_queue.pop do |query|
sql = query[:sql].is_a?(Proc) ? query[:sql].call(connection) : query[:sql]
connection.query(sql, query[:opts]).callback do |result|
query[:callback].call result if query[:callback]
queue_worker_loop.call connection
end
end
}
end
def start_queue(conf)
@pool_size.times do
connection = Mysql2::EM::Client.new(conf)
@connections << connection
queue_worker_loop.call connection
end
end
def query(sql, opts={}, &block)
@query_queue.push :sql => sql, :opts => opts, :callback => block
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment