0

我有一个 Spring Boot 应用程序,在其中创建了一个 POST 方法,该方法以流方式向调用者发送数据。下面的代码:

@RequestMapping(value = "/mapmatchstreaming", method = RequestMethod.POST)
public ResponseEntity<StreamingResponseBody> handleRequest(@RequestParam(value = "data", required = true) String data, @RequestParam(value = "mnr", required = true) Boolean mnr) {
    logger.info("/mapmatchstreaming endpoint");

    try {
        Semaphore semaphore = new Semaphore(1);
        ObjectMapper mapper = new ObjectMapper();

        StreamingResponseBody responseBody = new StreamingResponseBody() {
            @Override
            public void writeTo (OutputStream outputStream) throws IOException {
                // For each map
                DataReader dataReader = new DataReader(data, "2020.06.011");

                for(String mapRoot: dataReader.getMapsFolders()) {
                    dataReader = new DataReader(data, "2020.06.011");
                    DistributedMapMatcherStreaming distributedMapMatcher = new DistributedMapMatcherStreaming(dataReader.getTraces(), mapRoot, dataReader.getBoundingBox());
                    distributedMapMatcher.mapMatchBatch(new DistributedMapMatcherResult() {
                        @Override
                        public void onCorrectlyMapMatched(MapMatchedTrajectory mapMatchedTrajectory) {
                            try {
                                semaphore.acquire();
                                outputStream.write(mapper.writeValueAsString(mapMatchedTrajectory).getBytes());
                                outputStream.flush();
                            }
                            catch (Exception e) {
                                e.printStackTrace();
                                logger.error(String.format("Writing to output stream error: %s", e.getMessage()));
                            } finally{
                                semaphore.release();
                            }
                        }
                    });
                }
            }
        };

        return new ResponseEntity<StreamingResponseBody>(responseBody, HttpStatus.OK);
    }
    catch (Exception e) {
        logger.error(String.format("Map-matching result ERROR: %s", ExceptionUtils.getStackTrace(e)));
        return new ResponseEntity<StreamingResponseBody>(HttpStatus.BAD_REQUEST);
    }
}

它工作得很好,但问题是如果多个调用到达这个方法,即使我已经设置了所有这些调用都是并行运行的server.tomcat.threads.max=1。在非流式传输版本中,每个下一个调用都等待当前调用完成。

是否可以在 Spring 中阻止流式调用?谢谢。

编辑:我暂时通过使用只有 1 个许可证的全局信号量来解决,但我认为这不是理想的解决方案。

4

0 回答 0