0

我的springboot应用程序中有一个场景,我将任务提交到线程池以进行异步执行。现在子执行中的一些方法是@AfterReturn的方面点建议的一部分。我观察到即使处理是异步完成的,我的主线程也会继续执行来自子线程的切入点建议,并且我的服务不会返回值,直到所有子线程完成执行。任何指针如何使建议在执行线程本身上运行?所以简而言之,控制器方法在dao方法执行及其对应的切入点执行之前是不会返回响应的。

@Controller
@RequestMapping(value = "/api")
public class SampleController  {

@Autowired
SampleService service;
    @RequestMapping(value = "/action", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String action(@RequestBody String request){
     service.action(request);
     return "Success";
    }

}



@Service
public class SampleService{
@Autowired
SampleDao dao;

@Async("threadPoolExecutor")
public void action(String request){
 dao.action(request);
}

}


@Repository
public class SampleDao{
 public void action(String request){
 //do some db things
 }

}


@Aspect
@Component
public class SampleAspect{
@AfterReturning(
            pointcut = "execution( * com.sample.*.*.SampleDao.action(..))",
            returning = "result")
    public void audit(JoinPoint joinPoint, Object result)  {
       //dosome thing
    }



}
4

1 回答 1

0

on service 方法并不意味着它将被提交给 executor 服务然后@Async立即返回,但是您可以对端点进行多个传入调用,然后同时处理这些调用(这是默认情况下无论如何 afaik,@Async几乎只是一个标记)。

您可以阅读本指南以了解如何正确完成此操作。

要点是您的服务需要创建(并可选择返回)某种Future(在帖子的情况下,CompletableFuture,如

@Async
void serviceMethod(String request) {
    CompletableFuture.submit(() -> dao.action(request));
}

听起来您确实想等待结果到来,所以虽然这会起作用,但我希望您稍后会遇到问题。

于 2020-03-06T09:39:46.150 回答