根据this博客,可以避免阻止HTTP请求线程等待更长的IO,使其异步。在这里,单独的线程负责在结果可用时返回结果。基本实现如下
@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;
}
:
}
而不是&#34;执行&#34; (不带参数并返回结果),我想创建Callable使用带参数的方法并返回一些结果。像
Callable<String> callable = taskService.execute(request, headers);
如何实现这一目标?
答案 0 :(得分:1)
只需使用lambda:
Callable<String> callable = () -> taskService.execute(request, headers);
像这样:
@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;
}
}