我在play的Action中編寫了下面的包裝器,這個包裝器將使用一個同時需要會話和請求的函數。這是第一個版本:爲什麼下面的代碼泄漏一個Slick數據庫集合?
def ActionWithSession[A](bp: BodyParser[A])(f: Session => Request[A] => Result): Action[A] =
Action(bp) {
db.withSession {
session: DbSession =>
request => f(session)(request)
}
}
這個版本效果很好(正確的結果返回到瀏覽器),但每次調用會泄漏一個數據庫連接。幾個電話後,我開始下列情況除外:
java.sql.SQLException: Timed out waiting for a free available connection.
當我將其更改爲下面的版本(由行動後立即移動request =>
,連接泄漏消失了,和它的作品
def ActionWithSession[A](bp: BodyParser[A])(f: Session => Request[A] => Result): Action[A] =
Action(bp) { request =>
db.withSession {
session: DbSession =>
f(session)(request)
}
}
。
爲什麼第一個版本造成的連接泄漏,而第二個版本如何修復?
感謝您的解釋!這確實是一個容易犯的錯誤,也是一個棘手的錯誤。 – thesamet
你可能會對http://stackoverflow.com/questions/18579684/play-slick-and-async-is-it-a-race-condition感興趣,我認爲play-slick返回一個Future,它擁有對來自withSession塊的會話。 – thesamet