gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:05:00 26 4
gpt4 key购买 nike

我有一个方法只调用 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 将生成一个新线程(如果未配置线程池)并且同样,它不能继承父事务。因为,Spring Transaction 是以线程为基础的。

如果您将 @Transactional 与相关的传播值放在一起。这应该可以解决您的问题。

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

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

关于方法中带有 @Async 的 java.lang.IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56703699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com