从rails

时间:2016-01-30 12:23:41

标签: ruby-on-rails mongodb

我使用mongo驱动程序2.2.2从我的rails应用程序连接。 我注意到我有太多打开的连接。 这是我测试这个的方法:

@db = Mongo::Client.new('mongodb://user:password!@localhost:27017/db')
# nothing to do! only for test!
@db.close

我开始了 - rails app和mongodb

$ rails server
$ mongod

之后,我在调试模式下创建了对我的应用程序的单个请求并检查mongod输出:

2016-01-30T14:08:30.047+0200 [initandlisten] connection accepted from     127.0.0.1:65005 #1 (1 connection now open)
2016-01-30T14:08:30.048+0200 [conn1] end connection 127.0.0.1:65005 (0 connections now open)
2016-01-30T14:08:30.048+0200 [initandlisten] connection accepted from 127.0.0.1:65006 #2 (1 connection now open)
2016-01-30T14:08:30.051+0200 [initandlisten] connection accepted from  127.0.0.1:65007 #3 (2 connections now open)
2016-01-30T14:08:30.051+0200 [conn3] end connection 127.0.0.1:65007 (1 connection now open)
2016-01-30T14:08:30.051+0200 [initandlisten] connection accepted from  127.0.0.1:65008 #4 (2 connections now open)
2016-01-30T14:08:30.052+0200 [conn4] end connection 127.0.0.1:65008 (1 connection now open)

在我的rails输出中,我看到下一个:

D, [2016-01-30T14:08:30.046532 #12981] DEBUG -- : MONGODB | Adding localhost:27017 to the cluster.
D, [2016-01-30T14:08:30.050656 #12981] DEBUG -- : MONGODB | Adding localhost:27017 to the cluster.

我要关闭mongod并再次检查rails输出:

D, [2016-01-30T14:08:50.060270 #12981] DEBUG -- : MONGODB | IOError
D, [2016-01-30T14:09:00.065535 #12981] DEBUG -- : MONGODB | Connection refused - connect(2) for 127.0.0.1:27017
D, [2016-01-30T14:09:10.066730 #12981] DEBUG -- : MONGODB | Broken pipe
D, [2016-01-30T14:09:20.073243 #12981] DEBUG -- : MONGODB | Connection refused - connect(2) for 127.0.0.1:27017
D, [2016-01-30T14:09:30.079056 #12981] DEBUG -- : MONGODB | Broken pipe

最后我的问题是:如何真正关闭与mongo的连接? 我究竟做错了什么?

1 个答案:

答案 0 :(得分:2)

您可以使用池配置来限制连接数,如下所示:

@db = Mongo :: Client.new('mongodb:// user:password!@localhost:27017 / db?maxPoolSize = 10')

您可以在此链接https://docs.mongodb.com/ruby-driver/master/tutorials/ruby-driver-create-client/

上查看更多选项