简体   繁体   English

带参数的Spring MVC异步控制器实现

[英]Spring MVC async controller implementation with parameters

As per this blog, one can avoid blocking of HTTP Request thread from waiting for longer IO by making it asynchronous. 根据这篇博客,可以避免阻止HTTP请求线程等待更长的IO,使其异步。 Here, separate thread takes the responsibility of returning the result when it is available. 在这里,单独的线程负责在结果可用时返回结果。 The basic implementation is as follows 基本实现如下

@RestController
public class RequestController {

  private final TaskService taskService;

  private final Logger logger = LoggerFactory.getLogger(this.getClass());


  @Autowired
  public RequestController(TaskService taskService) {
    this.taskService = taskService;
  }

  @RequestMapping(value = "/callable", method = RequestMethod.GET, produces = "text/html")
  public Callable<String> executeSlowTaskWithCallable() {
    logger.info("Request received");
    Callable<String> callable = taskService::execute;
    logger.info("Servlet thread released");

    return callable;
  }
  :
}

Instead of "execute" (that takes no arguments and returns a result), I want to create Callable using method that takes arguments and returns some result. 而不是“执行”(不带参数并返回结果),我想创建Callable使用带参数的方法并返回一些结果。 Like 喜欢

Callable<String> callable = taskService.execute(request, headers);

How to achieve this ? 怎么做到这一点?

Just use a lambda: 只需使用lambda:

Callable<String> callable = () -> taskService.execute(request, headers);

Like so: 像这样:

@RestController
public class RequestController {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());
  private final TaskService taskService;

  @Autowired
  public RequestController(TaskService taskService) {
    this.taskService = taskService;
  }

  @RequestMapping(value = "/callable", method = RequestMethod.GET, produces = "text/html")
  public Callable<String> executeSlowTaskWithCallable() {
    logger.info("Request received");
    Object request, headers = // initialize variables
    Callable<String> callable = () -> taskService.execute(request, headers);
    logger.info("Servlet thread released");

    return callable;
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM