使用Java通过HTTP流数据

问题描述 投票:0回答:1

我有两个Java Spring Boot应用程序,我们将它们命名为Source和Consumer。源有一个GET端点/api/data,该端点返回无限的数据流。这个想法是从Consumer调用它,每隔几秒钟监听一次数据块,并且“永不”关闭此连接。我已经制作了一个简单的Source,目前看来可以使用:

@RestController
@RequestMapping ("/api")
public class SourceController {

    private final Logger logger = LoggerFactory.getLogger(SourceController.class);

    @GetMapping (value = "/data", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<StreamingResponseBody> data(final HttpServletResponse response) {
        response.setContentType("application/json");
        StreamingResponseBody stream = out -> {
            try {
                for (int i = 0; i < 10; i++) {
                    String content = "{\"counter\":" + i + "}\n";
                    out.write(content.getBytes());
                    logger.info("size: "  + content.getBytes().length);
                    Thread.sleep(1000);
                }
                out.close();
            } catch (final Exception e) {
                logger.error("Exception", e);
            }
        };
        logger.info("steaming response {} ", stream);
        return new ResponseEntity(stream, HttpStatus.OK);
    }
}

我不确定这是否正是我想要的,因为当我用Postman调用它时,在执行return的10秒钟后响应就会出现。

消费者阅读但阅读了整个响应,而不是一piece而就。

@RestController
@RequestMapping("/api")
public class ConsumerController {

    private final Logger logger = LoggerFactory.getLogger(ConsumerController.class);

    @GetMapping(value = "/consume", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> consume() throws IOException {
        URL url = new URL("http://localhost:8080/api/data");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream())
        );

        String decodedString;
        while ((decodedString = in.readLine()) != null) {
            logger.info(decodedString);
        }

        in.close();

        return new ResponseEntity("ok", HttpStatus.OK);
    }
}
java spring-boot reactive-programming http-live-streaming
1个回答
0
投票

源看起来正确,但是您只是忘记在向其中写入数据块之后刷新OutputStream,因此使用者无法立即接收到该数据块。

因此将一些内容写入flush()后调用OutputStream应该可以解决问题:

 for (int i = 0; i < 10; i++) {
       String content = "{\"counter\":" + i + "}\n";
       out.write(content.getBytes());
       out.flush();
       logger.info("size: "  + content.getBytes().length);
       Thread.sleep(1000);
}

© www.soinside.com 2019 - 2024. All rights reserved.