java调用方法而不等待响应

vybvopom  于 2021-07-15  发布在  Java
关注(0)|答案(1)|浏览(506)

在另一个方法之后执行一个方法而不是等待其执行的最佳方法是什么:
例如,我有一个spring boot api:

@GetMapping("/users/{performanceCode}")
@ResponseBody
public ResponseEntity<UserDTO> getUserPerformance(@PathVariable String performanceCode) {
    return new ResponseEntity(userService.getUserPerformance(performanceCode), HttpStatus.OK);
}

userService.getUserPerformance(performanceCode) 我必须做些什么

@Transactional
    public UserDTO getUserPerformance(String performanceCode) {
      UserDTO  userDTO = // some logic..... ;

      //... some other code

      // here  I call this method that I don't have to wait for it to finish and also if it throws an error I shouldn't block the whole service to return error 
      userCalculationsService.resetUserPerformances(userDTO );
      return userDTO;
}

所以我的问题是我想打电话 userCalculationsService.resetUserPerformances(userDTO ) 但是我不想等到它完成,或者如果它在方法中抛出错误,我不应该阻止整个服务返回错误。
有人能帮我处理这件事吗?

dy2hfwbg

dy2hfwbg1#

在springboot应用程序主类中:

@EnableAsync
@SpringBootApplication(scanBasePackages = {<packages......>})
public class Application {

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

  @Bean(name = "taskExecutor")
  public Executor taskExecutor() {
    final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(100);
    executor.setThreadNamePrefix("Thread-");
    executor.initialize();
    return executor;
  }

在控制器中,可以调用异步方法:

@RestController
@RequestMapping("/invoke-command")
public class SlashCommandController extends BotClass {

  @Autowired
  AsyncService async;

  // To invoke Commands using SlashCommand
  @RequestMapping(value = "/{commandName}", method = RequestMethod.POST,
      consumes = MediaType.ALL_VALUE)
  public String runCommands(@RequestParam Map<String, String> request,
      @PathVariable String commandName) throws Exception {
    async.runCommands(request, commandName);

    return "HAHA";
  }

}

异步服务类:

@Service
public class AsyncService {

  // Asynchronous Service for SlashCommands
  @Async("taskExecutor")
  public void runCommands(Map<String, String> request, String commandName)
      throws IllegalAccessException, IllegalArgumentException, InvocationTargetException,
      FileNotFoundException, IOException, ParseException {
   //doSomething
  }
}

相关问题