小编Nor*_*csi的帖子

当客户端与热流断开连接时执行一些操作

我做了一个简单的 Spring Boot 应用程序。我有一个 REST 端点,它返回当前时间的热流。

@RestController
public class NowResource {

    @GetMapping(value = "/now", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> now() {
        return Flux.interval(Duration.ofSeconds(1))
            .flatMap(t -> Flux.just(Instant.now().toString()));
    }

}
Run Code Online (Sandbox Code Playgroud)

当我打电话时,http://localhost:8080/now我得到一个数据流,如下所示:

数据:2018-04-03T13:20:38.313222100Z

数据:2018-04-03T13:20:39.311493500Z

数据:2018-04-03T13:20:40.310878800Z

...

当我与流断开连接(关闭浏览器选项卡)时,IOException会抛出、捕获并打印堆栈跟踪。

java.io.IOException:已建立的连接被主机中的软件中止

...

我尝试过捕获它,但它已经被捕获并且没有返回到我的方法。

我尝试在 Flux 中添加等doOnTerminate()doOnError()但似乎没有任何效果,我猜测实际事件是不同类型的。

我可以以某种方式访问​​此异常,以不同于仅打印它的方式处理它吗?(我想避免在日志中输出 200 多行,而只打印“DONE”。)

编辑:我的解决方案基于托马斯·皮诺斯的答案

我最终采用了这种方法,不同之处在于我将其移至一个新类,这样它就可以处理来自所有控制器的所有此类异常。

@Slf4j
@ControllerAdvice
class IOExceptionHandler implements WebExceptionHandler {

    @ExceptionHandler(IOException.class)
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        return Mono.just(ex.getMessage())
            .doOnNext(
                msg -> log.warn("IOException occurred: {}.", msg)
            )
            .then();
    } …
Run Code Online (Sandbox Code Playgroud)

java spring reactor spring-webflux

5
推荐指数
1
解决办法
1037
查看次数

Spring Boot - 多部分 - 不支持的媒体类型

我想在一个帖子请求中发送一个文件和一个 json 模型。

我的请求映射如下所示:

    @PostMapping("{id}/files")
    public MyOutput create(@PathVariable String id, @RequestPart("request") MyInput input, @RequestPart("file") MultipartFile file) {
    // ...
    }
Run Code Online (Sandbox Code Playgroud)

我收到的错误:

{
    "timestamp": "Feb 7, 2019, 3:18:50 PM",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/octet-stream' not supported",
    "trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported...,
    "path": "/tests/12345/files"
}
Run Code Online (Sandbox Code Playgroud)

邮递员请求:http : //imgshare.free.fr/uploads/62f4cbf671.jpg

我的网络配置:

    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {

        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.setPrettyPrinting().create();

        final GsonHttpMessageConverter msgConverter = new GsonHttpMessageConverter();
        msgConverter.setGson(gson);
        msgConverter.setDefaultCharset(StandardCharsets.UTF_8);
        converters.add(msgConverter); …
Run Code Online (Sandbox Code Playgroud)

java rest spring-boot

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×2

reactor ×1

rest ×1

spring ×1

spring-boot ×1

spring-webflux ×1