Spring Boot @Async方法同步执行

时间:2015-09-14 09:36:28

标签: java spring spring-boot

这与此处的其他问题非常相似:Spring Boot @Async method in controller is executing synchronously。但是,使用@Service注释的@Async方法仍在同步执行。我尝试过来自不同论坛的所有方法都没有用。希望有人可以帮我找出原因。如下的简单弹簧启动项目不起作用。

AsyncConfiguration.java

@Configuration
@EnableAsync
public class AsyncConfiguration(){}

SomeService.java

@Service
public class SomeService() {
  @Async
  public void doSomething() {
    try {
      Thread.sleep(5000L);
    } catch (Exception ignore){}
  }
}

SomeController.java

@Controller
public class SomeController() {

  @Inject SomeService someService;

  @RequestMapping(value="/", method=RequestMethod.POST)
  public String doStuff() {
    someService.doSomething();
    return "mytemplate";
  }
}

2 个答案:

答案 0 :(得分:1)

以下是@Async的简单示例。按照以下步骤使@Async在Spring Boot应用程序中运行:

步骤1:添加@EnableAsync注释并将TaskExecutor Bean添加到应用程序类。

示例:

@SpringBootApplication
@EnableAsync
public class AsynchronousSpringBootApplication {

    private static final Logger logger = LoggerFactory.getLogger(AsynchronousSpringBootApplication.class);

    @Bean(name="processExecutor")
    public TaskExecutor workExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("Async-");
        threadPoolTaskExecutor.setCorePoolSize(3);
        threadPoolTaskExecutor.setMaxPoolSize(3);
        threadPoolTaskExecutor.setQueueCapacity(600);
        threadPoolTaskExecutor.afterPropertiesSet();
        logger.info("ThreadPoolTaskExecutor set");
        return threadPoolTaskExecutor;
    }

    public static void main(String[] args) throws Exception {
  SpringApplication.run(AsynchronousSpringBootApplication.class,args);
 }
}

步骤2:添加执行异步处理的方法

@Service
public class ProcessServiceImpl implements ProcessService {

    private static final Logger logger = LoggerFactory.getLogger(ProcessServiceImpl.class);

    @Async("processExecutor")
    @Override
    public void process() {
        logger.info("Received request to process in ProcessServiceImpl.process()");
        try {
            Thread.sleep(15 * 1000);
            logger.info("Processing complete");
        }
        catch (InterruptedException ie) {
            logger.error("Error in ProcessServiceImpl.process(): {}", ie.getMessage());
        }
    }
}

步骤3:在Controller中添加API以执行异步处理

@Autowired
private ProcessService processService;

@RequestMapping(value = "ping/async", method = RequestMethod.GET)
    public ResponseEntity<Map<String, String>> async() {
        processService.process();
        Map<String, String> response = new HashMap<>();
        response.put("message", "Request is under process");
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

我还在GitHub上写了一个博客和一个有用的应用程序。请检查: http://softwaredevelopercentral.blogspot.com/2017/07/asynchronous-processing-async-in-spring.html

答案 1 :(得分:0)

对不起,我的英语。 我也遇到了同样的问题。 解决方法是添加

@Autowired
private SomeService someService;

在Controller类中,通过这种方式,它允许该类包含与“ SomeService”相关联的Beam配置,从而能够完美地执行异步方法。

这是一个具有功能异步方法的项目: https://github.com/JColmenares/async-method-api-rest.git

相关问题