簡體   English   中英

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

[英]java.lang.IllegalStateException with @Async in method

我有一個僅在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,則代碼可以正常運行

@Async將產生一個新線程(如果未配置線程@Async ),並且相同,它不能繼承父事務。 因為,Spring Transaction是基於每個線程的。

如果您將@Transactional與相關的傳播值放在一起。 這應該可以解決您的問題。

除非它非常關鍵,否則我不會推薦這種事務管理方式。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM