How to use Lwt_pool

212 views Asked by At

I want to have a pool of Redis database connections with a max number of connections. It looks like Lwt_pool is the solution I am looking for, but I don't quite grasp how it should work. For example, some questions I have:

  • The docs talk about Lwt_pool being great to reuse open connections, but how does the pool know what connections are available for reuse? As far as I see, there is no particular way to signal that and the API only provides the use method.

  • Is there any resource better than the Lwt docs to learn how it works? I can't easily find code examples or many resources available about it.

1

There are 1 answers

1
Thomas Leonard On BEST ANSWER
  • The function you pass to use returns a thread. When the thread finishes, the connection is released back to the pool.

  • The source code is fairly easy to read. In this case:

    let use p f =
      acquire p >>= fun c ->
      Lwt.catch
        (fun () ->
           let t = f c in
           t >>= fun _ ->
           release p c;
           t)
        (fun e ->
           checked_release p c;
           Lwt.fail e)