Friday, January 18, 2008

Rails multi-database connections resolutions

当Rails项目中数据处理量比较大时就需要将数据库的读写操作分在不同的database server上,在网上GOOGLE了一下,主要通过Dr.Nic的magic_multi_connections来处理,需要安装这个GEM包,然后修改config/database.yml,config/environment.rb文件,具体可参考Dr.Nic的说明,还是比较方便的.
还有个是叫active_delegate的Rails plugin,使用比上面的gem更方便,但是实际使用后发现没有Dr.Nic的方法好用.

Update: Nic的方法使用起来修改配置的地方还是比较多,实际使用过程中发现还是有点问题的.建议还是按rails本身提供的一个多数据库连接机制:
Connection to multiple databases in different models
Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. For example, if Course is a ActiveRecord::Base, but resides in a different database you can just say Course.establish_connection and Course *and all its subclasses* will use this connection instead.

This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.

No comments :