(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()); } }