我遇到了一个问题,我的 Scotty 应用程序似乎没有终止旧的 HTTP 请求线程。最终,在大量(10-20)个并发请求之后,我遇到了一个错误 with too many DB connections libpq: failed (FATAL: sorry, too many clients already)
。
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Database.PostgreSQL.Simple
import Control.Monad.IO.Class
connection :: IO Connection
connection = connect defaultConnectInfo
{ connectHost = "localhost", connectUser="postgres", connectPassword="mysecretpassword" }
main :: IO ()
main = scotty 8000 $ do
get "/" $ do
c <- liftIO $ connection
text "test"
这也发生在 Warp 应用程序(Scotty)中:
{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Network.Wai.Handler.Warp (run)
import Network.HTTP.Types (status200)
import Network.HTTP.Types.Header (hContentType)
import Database.PostgreSQL.Simple
import Control.Monad.IO.Class
connection :: IO Connection
connection = connect defaultConnectInfo
{ connectHost = "localhost", connectUser="postgres", connectPassword="mysecretpassword" }
main = run 8000 app
app :: Application
app req respond = do
respond $ responseStream status200 [] $ \write flush -> do
print "test"
con <- connection
flush
write $ "World\n"
为什么会这样?有没有一种简单的方法可以在最后“完成”请求?
我可以手动关闭连接,但理想情况下,我认为用任何其他相关资源终止线程是理想的。
我已经通过在 postgres 中运行以下命令来验证它是否保持连接打开:
SELECT sum(numbackends) FROM pg_stat_database;
Scotty 似乎需要几秒钟才能自动关闭它(在请求完成后)。