我有一个小型Scotty应用程序,它使用MongoDB连接到persistent数据库(该应用程序托管在Heroku上并使用MongoLab数据库)。我是这个相对低级别的数据库交互世界的新手;以前我用的是Yesod,其中大部分细节都是抽象的。我想问一下我使用数据库连接池的方法是否合适!
应用程序在main
函数中设置,基本上就是这样:
main = withMongoDBPool ... $ \pool -> scotty 8000 (app pool)
我省略了withMongoDBPool
的大量参数。然后,应用程序代码在调用runMongoDBPool
:
app pool = do
get "/:id" $ do
itemId <- param "id"
item <- runDB $ selectFirst [ItemIdent ==. itemId] []
case item of
Just _ -> text "found it :)"
Nothing -> text "not found :(" >> status notFound404
where
runDB action = liftIO $ runMongoDBPool master action pool
在之前的代码中,我会在withMongoDBPool
中使用runDB
,但是根据我的理解,它会为runDB
的每次调用创建一个新的连接池。我只是想验证这种方法是数据库连接池的预期用途,特别是persistent-mongoDB
的接口。
实际代码为here。