Spring Webflux 是否在每个请求的单个线程中调用单个 HandlerFunction?

Does Spring Webflux invokes single HandlerFunction in a single thread per request?

考虑下面的代码片段 - 将简单的非线程安全的 HashMap 传递给将在 SomeHandlerFunction 中的其他自动装配 bean 中使用它的 SomeHandlerFunction 是否安全?

@Bean
RouterFunction<ServerResponse> request(SomeHandlerFunction handlerFunction) {
    handlerFunction.setSimpleMapProperties(new HashMap());
    return route(GET("/dummy"), handlerFunction);
}


@Service
class SomeHandlerFunction implements HandlerFunction {
    @Autowired
    List<AnotherBeans> anotherBeans;

    Mono<T> handle(ServerRequest var1) {
        // code...
    }
}

我对 WebFlux 中的多线程模型有所了解,但是这个案例让我感到困惑。

如果 HashMap 是可变的,这不是一个好主意 - 即使使用 Spring MVC 也是如此。 你应该怎么做呢?这实际上取决于手头的用例。

如果您尝试设置本地内存缓存,您可以使用像 Caffeine 这样的库,或者只是 ConcurrentMapCache

如果您想与那个 bean 共享配置键,您可以用 Collections.unmodifiableMap 包装那个映射,甚至更好,使它成为一个适当的不可变 POJO。

如果这是为了携带与正在处理的请求链接的临时数据,您应该改为使用请求属性或 Reactor Context。