方法中带有@Async的java.lang.IllegalStateException

时间:2019-06-21 12:42:48

标签: java spring-boot

我有一个仅在mysql中调用过程的方法。这是我的代码:

import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
import javax.transaction.Transactional;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class ClientService {

    @PersistenceContext
    protected EntityManager entityManager;

    @Async
    public void callFunction(Integer clientId) {

        StoredProcedureQuery query = entityManager.createStoredProcedureQuery("myProcedureSql");
        query.registerStoredProcedureParameter("clientId", Integer.class, ParameterMode.IN);
        query.setParameter("clientId", clientId);
        query.execute();
    }

}

我需要它异步运行,但是当我将@Async标记放入方法中时,它失败,给我以下错误:

196536 [SimpleAsyncTaskExecutor-2] ERROR org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler  - Unexpected error occurred invoking async method 'public void ar.com.lemondata.turnero.backend.service.PruebaService.procesarCSV()'.
org.springframework.dao.InvalidDataAccessApiUsageException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

如果我删除@Async,则代码可以完美运行

1 个答案:

答案 0 :(得分:0)

@Async将产生一个新线程(如果未配置线程池),并且该线程不能继承父事务。因为,Spring Transaction是基于每个线程的。

如果您将@Transactional设置为相关的传播值。这应该可以解决您的问题。

除非它非常关键,否则我不会推荐这种事务管理方式。

https://dzone.com/articles/spring-async-and-transaction