简体   繁体   中英

Springboot JPA Repository not releasing Hikari DB Connection

I have a rest API in Springboot using Hikari for connection pooling. Hikari is used with default configurations (10 connections in the pool, 30 sec timeout waiting for a connection). The API itself is very simple

  1. It first makes a JPA repository query to fetch some data from a PostgresDB. This part takes about 15-20milliseconds.
  2. It then sends this data to a remote REST API that is slow and can take upwards of 120seconds.
  3. Once the remote API responds, my API returns the result back to the client. A simplified version is shown below.
    public ResponseEntity analyseData(int companyId) {
        Company company = companyRepository.findById(companyId);//takes 20ms
        Analysis analysis = callRemoteRestAPI(company.data) //takes 120seconds
       return ResponseEntity.status(200).body(analysis);

    }

The code does not have any @Transactional annotations. I find that the JDBC connection is held for the entire duration of my API (ie ~ 120s). And hence if we get more than 10 requests they timeout waiting on the hikari connection pool (30s). But strictly speaking my API does not need the connection after the JPA query is done (Step 1 above).

Is there a way to get spring to release this connection immediately after the query instead of holding it till the entire API finishes processing? Can Spring be configured to get a connection for every JPA request? That way if I have multiple JPA queries interspersed with very slow operations the server throughput is not affected and it can handle more than 10 concurrent API requests. .

Essentially the problem is caused by the Spring OpenSessionInViewFilter that " binds a Hibernate Session to the thread for the entire processing of the request " This essentially acquires a connection from the pool when the first JPA query is executed and then holds on to it till the request is processed.

This page - https://www.baeldung.com/spring-open-session-in-view provides a clear and concise explanation about this feature. It has its pros and cons and the current opinion seems to be divided on its use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM