我构建了一个自定义 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调用 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 数据写入响应流,请求仍然会终止。正如您已经知道使用它们的后果一样。如果这确实会给您带来任何问题,那么您可以考虑 MappingJackson2HttpMessageConverter相反,它不会close将 json 字符串写入其中后的输出流。
但是如果您编写一个新的转换器,那么最好不要在代码中的任何位置关闭流。
关于java - 我是否需要刷新或关闭自定义 Spring Web MessageConverter 中的 OutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37937583/