user6324692
user6324692

Reputation:

Luminus -- multiple requests within the same db connection

In my Luminus app I have this:

(defn page1 [id]
  (layout/render "page1.html" 
    {:article (db/get-single-article {:id (Integer/parseInt id)}))

I want to perform multiple different requests to the db within the same db connection. How can I do that?

Upvotes: 0

Views: 99

Answers (1)

Piotrek Bzdyl
Piotrek Bzdyl

Reputation: 13175

From your question it's not clear whether you want to reuse the same DB connection to handle multiple HTTP requests or single HTTP request calling multiple functions using JDBC API (so all those JDBC calls use the same DB connection).

If this is the latter case you can use with-db-connection to wrap all your functions calling JDBC API. You can also use with-db-transaction if all SQL operations should be part of one DB transactions.

For the former case I am not sure why you would need to reuse the same connection for multiple HTTP requests but it is not a common idiom as HTTP is stateless by definition and causes multiple issues.

You might store the connection in your ring HTTP session so you can fetch it whenever you get a request associated with the session and use for JDBC logic.

However, such a solution has following drawbacks:

  • you have to make sure that the connection gets released to the pool (or closed if you don't use pooling) when is no longer needed. How would you detect that? What if the client fails and never finishes some workflow where you decide to clean up the DB connection?
  • how many concurrent 'sessions' do you need to handle? If many (like hundreds) keeping a dedicated connection for each session won't scale (DB connections are expensive resources on both sides: client and servers)

Upvotes: 1

Related Questions