Created
August 25, 2011 18:13
-
-
Save jschoolcraft/1171341 to your computer and use it in GitHub Desktop.
a simple connection pool for eventmachine & mysql2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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