gpt4 book ai didi

java - Spring MVC 中的延迟计算

转载 作者:行者123 更新时间:2023-11-30 06:39:10 28 4
gpt4 key购买 nike

假设我有一些服务 S 接收来自客户端 C 的请求。S由于计算量大,无法立即响应,C也不能永远等待,有自己的超时时间。

我的想法是实现服务器端,如下所述: REST and long running jobs, Farazdagi

在我的 ServerController 中,我有一个用于延迟计算的线程池和一个用于存储响应的并发映射。

private final int NUMBER_OF_WORKERS = 10;
private Map<String, ResponseEntity<MathResponse>> responseMap = new ConcurrentHashMap<>();
private ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_WORKERS);

我的 /calculate 映射将作业提交到线程池并返回 202(已接受) HTTP 状态,并将重定向链接放置到 Location header .

@RequestMapping(value = "/calculate", method = RequestMethod.POST)
public ResponseEntity<String> startWorkflow(@RequestBody MathRequest request, UriComponentsBuilder builder) {
UUID uuid = UUID.randomUUID();
executorService.submit(() -> {
// time-consuming calculations here
ResponseEntity<MathResponse>response = HardMath.execute(request)
responseMap.put(uuid.toString(), response);
});

HttpHeaders headers = new HttpHeaders();
UriComponents uriComponents = builder.path("/wf/queue/{id}").buildAndExpand(uuid.toString());
headers.setLocation(uriComponents.toUri());
return new ResponseEntity<>(headers, HttpStatus.ACCEPTED);
}

/queue/id 映射中,如果结果在 map 中,我将返回结果:

@RequestMapping(value = "/queue/{id}", method = RequestMethod.GET)
public ResponseEntity<MathResponse> getQueueInfo(@PathVariable("id") String id) {
ResponseEntity<MathResponse> defaultQueueResponse = new ResponseEntity<>(new MathResponse(), HttpStatus.OK);
return responseMap.getOrDefault(id, defaultQueueResponse);
}

我认为使用像ConcurrentHashMap这样的低级东西并不是一个好主意。 Spring 中有没有我可以使用的选项,而不是重新发明轮子?

最佳答案

还有一个弹性问题;如果结果是 S 实例本地的(即在进程内 Map 中),那么如果 S 实例崩溃或重新启动,则结果将丢失,并且 C 将被迫重新提交其请求。如果 S 中的结果缓存由弹性存储支持,那么结果可以在 S 崩溃/重新启动时幸存下来。

Spring 的caching abstraction使用<在此处插入存储技术>的后备存储可能会有所帮助。

关于java - Spring MVC 中的延迟计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44691256/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com