On 8/8/06, snacktime <snacktime at gmail.com>
wrote:>
> I grabbed some code off the net and modified it to come up with a
> connection pool that uses ruby-dbi.
>
> Start the pool like this:
>
> @@pool = Dbpool::ConnectionPool.get_instance(:Connections=>3)
>
> Then you can do your database calls like this:
>
> @pool.open {|conn|
> ## db operations here
> }
>
> Or like this:
>
> conn = @@pool.get_connection
> ## db operations here
> @@pool.release conn
>
>
>
----------------------------------------------------------------------------------
> require ''thread''
> require ''dbi''
> module Dbpool
> :User => ''username'',
> :Password => ''password'',
> :ConnString =>
''dbi:Pg:dbname=test;host=localhost'',
> :Connections => 3,
>
> class ConnectionPool
> @@instance = nil
> @@instance_mutex = Mutex.new
> @@instance ||= self.new(config)
> }
> end
>
> def initialize(config=Database)
> @num_busy = 0
> @max_allowed = @config[:Connections]
> @monitor_mutex = Mutex.new
> @free_mutex = Mutex.new
> @free_connections.push create_connection
> }
> end
>
>
> @free_connections.size
> }
> end
>
> release connection
> end
>
>
> def get_connection
> @busy_mutex.synchronize {
> while @free_connections.empty?
> sleep(0.001)
> end
> @free_connections.pop
> }
> end
>
>
> def release(connection)
> @free_mutex.synchronize {
> @free_connections.push connection
> }
> end
>
> protected
>
> def create_connection
> DBI.connect(@config[:ConnString],
> @config[:User], at config[:Password], ''AutoCommit'' =>
false)
> end
> end
>
>
> class LenientConnectionPool < ConnectionPool
>
> def get_connection
> @busy_mutex.synchronize {
> if @free_connections.empty?
> create_connection
> else
> @free_connections.pop
> end
> }
> end
>
> end
> end
> _______________________________________________
> Eventmachine-talk mailing list
> Eventmachine-talk at rubyforge.org
> http://rubyforge.org/mailman/listinfo/eventmachine-talk
>
Thanks, Snacktime. I''ll see if I can integrate this code with EM.
-------------- next part --------------
An HTML attachment was scrubbed...
URL:
http://rubyforge.org/pipermail/eventmachine-talk/attachments/20060808/1ae4a11c/attachment.html