I’m writing a Rails application which does not have a web frontend
(no controllers and no views, only models). Rather, it is a faceless
server, supporting many tens of thousands of threads and socket
connections. Some of these are fairly short-lived, perhaps a second
or two at the most, but the majority of them live longer, possibly up
to several hours or more.
Writing a server application in Rails has its advantages - among them
is the testing framework, and of course the abstractions provided by
ActiveRecord.
However, it is impractical to allot a database connection per thread,
since there are so many of them. And most of the work done in a
thread involves manipulation of ActiveRecord objects only initially,
at the start of a thread’s life, and perhaps a couple of times
thereafter.
For this application, it would make sense to close the db connection
and reopen it when needed.
My question to those of you who know about the inner workings of
ActiveRecord is: what is the best way of disconnecting from the
database? Of course, I can wrap all ActiveRecord accesses in blocks,
like this:
with_connection do { MyModel.find(:all).each … }
where with_connection could be defined as
def with_connection
begin
ActiveRecord::Base.establish_connection
result = yield
ensure
ActiveRecord::Base.remove_connection
end
result
end
With_connection could of course also maintain a pool of connections.
But is there a configuration alternative that automatically makes
ActiveRecord drop the connection after each query?
I should add that ActiveRecord::Base.allow_concurrency = true, and
that the db is Postgres, with concurrency enabled in the database.yml
file.
/ Peter B.