【问题标题】:Does Spring Webflux invokes single HandlerFunction in a single thread per request?Spring Webflux 是否在每个请求的单个线程中调用单个 HandlerFunction?
【发布时间】:2018-11-04 21:18:53
【问题描述】:

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

@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 中的多线程模型有点了解,但是这个案例让我很困惑。

【问题讨论】:

  • 不,无论使用何种技术,这样做都不安全。

标签: java spring multithreading spring-webflux reactor


【解决方案1】:

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

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

如果您想与该 bean 共享配置密钥,您可以使用 Collections.unmodifiableMap 包装该映射,甚至更好,使其成为适当的不可变 POJO。

如果这是为了携带与正在处理的请求相关联的临时数据,则应改为使用请求属性或 Reactor Context。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 2019-12-10
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多