我是否需要刷新或关闭自定义 Spring Web MessageConverter 中的 OutputStream

Do i need to flush or close the OutputStream in my custom Spring Web MessageConverter

我构建了一个自定义 Spring Web MessageConverter 并覆盖了 writeInternal 方法。

我应该在 getBody() OutputStream 上调用 flush 吗? 我应该关闭 getBody() OutputStream 吗?

不同的转换器之间似乎存在很大的不匹配。

我想两者都不要,因为 spring 想刷新输出流见 https://github.com/spring-projects/spring-framework/blob/56db1af11dbe51c88c753421e022bc5389361c04/spring-web/src/main/java/org/springframework/http/converter/AbstractGenericHttpMessageConverter.java#L101

但后来我看到 gson 实际上正在关闭流?那只是一个错误还是所需的行为? https://github.com/spring-projects/spring-framework/blob/56db1af11dbe51c88c753421e022bc5389361c04/spring-web/src/main/java/org/springframework/http/converter/json/GsonHttpMessageConverter.java#L203

然后 StringConverter 刷新但不关闭 https://github.com/spring-projects/spring-framework/blob/56db1af11dbe51c88c753421e022bc5389361c04/spring-web/src/main/java/org/springframework/http/converter/StringHttpMessageConverter.java#L107 which calls https://github.com/spring-projects/spring-framework/blob/56db1af11dbe51c88c753421e022bc5389361c04/spring-core/src/main/java/org/springframework/util/StreamUtils.java#L110

所以在现有技术中并没有真正看到明确的答案...

切勿在任何地方调用 close() 方法。

You should never call close() method as it will immediately disconnect the client socket and their will be no point executing request further on server as the client request is already processed. Also it will trimmed out all the configured post filters and interceptors execution that may results in various error condition.

Why should we not call close method on response stream/writer?

响应流最终将在请求处理结束时由容器本身关闭,因此您不必担心手动调用它。只需编写您想要的自定义转换器即可。

此外,您不需要将内容刷新为缓冲输出流,当缓冲区容量用完时,内容会自动刷新。

Gson 转换器可能有误,一旦 json 数据写入响应流,请求仍将终止。正如您已经知道使用它们的后果。如果这真的会在您的情况下造成任何问题,那么您可以在将 json 字符串写入其中后考虑 MappingJackson2HttpMessageConverter as alternative, it doesn't close 输出流。

但是如果您编写一个新的转换器,那么最好不要在代码中的任何地方关闭流。