问题
I just started with Ruby and I am playing with Sinatra, but could not find a way to share database connections between requests.
I came from Java web developement and one of the basic things you have to do is to pool the database connections, so I am sure that something similar exists in Ruby, but I just can't find it.
ActiveRecord and DataMapper offer this feature but I don't need ORM and just want to make regular SQL queries.
Is there some specific approach for Sinatra or there are general ways for all Rack-based applications?
回答1:
To persist a connection, you need only create an instance variable (Sinatra Applications are just objects anyway) or a global variable. Or a class that manages connections for you. Most Ruby database libraries I've seen are Database Adapters or just clients.
@db = Mysql2::Client.new #...
Or a global variable:
$db = Mysql2::Client.new #...
Connection pooling is just a way to share a small number of connections across multiple threads/fibers for the lifespan of the application. Java, the JVM, as far as I know doesn't share connections between processes.
However, there is a general purpose Connection Pool library for Ruby.
来源:https://stackoverflow.com/questions/11993241/database-connection-pooling-in-ruby