当使用monger时,我需要提供连接每个请求吗? [英] When using monger, do I need to supply connection each request?
问题描述
在文档中,mongodb连接建立一次,在使用之前不传递连接对每个命令,是否正确的方式使用monger,或者应该将数据库连接传递给每个调用?
In the documentation, the mongodb connection is established once, before being used without passing the connection to each command, is that the proper way to use monger, or should I pass the database connection to each call?
推荐答案
你使用单个数据库,那么最好设置连接一次:
If you work with single database then it's best to set the connection once:
(mg/connect! db-spec)
但是这不是一个好主意,当你有多个数据库。 Monger有 with-connection
巨集(参阅API文件):
But it's not a good idea when you have multiple databases. Monger have with-connection
macro (see API docs) for this case:
(mg/with-connection db-connection
...)
您可以在应用程序初始化期间建立所有连接:
You may establish all connections once during the initialization of your app:
(def conn1 (mg/connect db-spec))
然后使用它们:
(mg/with-connection conn1
...)
更新。在我们的应用程序中,数据库连接:
Update. In our application we have a hash-map of all database connections:
(def ^:dynamic
^clojure.lang.PersistentArrayMap
*connections*
{})
(defn connect! [db]
{:pre [(contains? mongo-config db)]}
(if (-> db *connections* nil?)
(let [conn (mg/connect (get mongo-config db))]
(alter-var-root #'*connections*
assoc
db
{ :conn conn
:db (mg/get-db conn (name db))})))
(-> *connections* db :conn))
(defmacro with-db [db & body]
"Eval body using :amonplus or :statistic db"
`(mg/with-connection (connect! ~db)
(mg/with-db (clojure.core/-> *connections* ~db :db)
~@body)))
mongo-config
变量存储我们所有数据库的规范, with-db
宏可以通过名称轻松访问它们:
mongo-config
variable stores specification for all our databases and with-db
macro makes it easy to access them by their names:
(with-db :my-db
...)
这篇关于当使用monger时,我需要提供连接每个请求吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!