Hello,
How would you handle DB connections within a HTTP request using Opium web framework?
I’m trying to use Redis driver and I’m getting weird results. Like requests are being cached, and no new connection to DB is made on every request.
Thanks
Hello,
How would you handle DB connections within a HTTP request using Opium web framework?
I’m trying to use Redis driver and I’m getting weird results. Like requests are being cached, and no new connection to DB is made on every request.
Thanks
I don’t know about Redis on particular, but I recommend to have a pool of connections constantly, and keeping them open all the time (in case you have a lot of traffic between app and DB).
You will need something like:
module Pool = struct
type t = connection (* your type *) Lwt_pool.t
let connect info =
Lwt_preemptive.detach (fun () ->
try Ok (new DB.connection (* your DB function *) info ())
with Error e -> Error e
let create info size () =
Lwt_pool.create size (fun () ->
connect info () >>= function
| Ok con ->
(* some code *)
>>= fun () -> Lwt.return con
| Error e ->
failwith @@ e
)
let use f pool =
Lwt_pool.use pool (f)
end
And then you can use Pool.use
:
Pool.use (
Lwt_preemptive.detach (fun c -> (* some code *) c)
) pool
Sorry if there are mistakes - I wrote it schematically, might be wrong in some places.