Solved the problem of DeferredResult request taking up database connection for a long time

I recently looked at the source code of the open source project appllo configuration center and found something very interesting:

(1) Principle: Due to the use of DeferredResult, according to the default logic of Spring DispatcherServlet, the database connection is only available when the asynchronous request is actually returned to the client. It will be released back to the connection pool

(2) Application scenario: The long connection time is very long, and it may take more than several hours for most requests to return. It is unreasonable to occupy the database connection for such a long period of time.

Long connection scenario solution:

@Component
public class EntityManagerUtil extends EntityManagerFactoryAccessor {
  private static final Logger logger = LoggerFactory.getLogger(EntityManagerUtil.class);
  /**
   * close the entity manager.
   * Use it with caution! This is only intended for use with async request, which
   * Spring won't close the entity manager until the async request is finished.
   */
  public void closeEntityManager() {
    EntityManagerHolder emHolder = (EntityManagerHolder)
        TransactionSynchronizationManager.getResource(getEntityManagerFactory());
    if (emHolder == null) {
      return;
    }
    logger.debug("Closing JPA EntityManager in EntityManagerUtil");
    EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
  }
}


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327042661&siteId=291194637