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

标签 java spring multithreading spring-webflux reactor

考虑下面的代码片段 - 将简单的非线程安全 HashMap 传递给将在 SomeHandlerFunction 中的其他 Autowiring 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.unmodifyingMap 包装该映射,甚至更好,将其设为适当的不可变 POJO。

如果这意味着携带与正在处理的请求链接的临时数据,您应该使用请求属性或 react 器上下文。

关于java - Spring Webflux 是否在每个请求的单个线程中调用单个 HandlerFunction?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53145566/

相关文章:

java - NoClassDefFoundError org.hibernate.engine.spi.SharedSessionContractImplementor 同时使用 hibernate 5.1.0 和 Spring 5.1.3

c# - 从即时窗口进行多线程调试

javascript - NodeJS - 是否可以有两个独立的集群?

java - java封装的要点

java - 正则表达式不匹配重复数字

java - 我的代码运行,但当我比较两个数组的内容时,if 语句没有打印其内容

java - 模拟空对象而不传递它们

java - Spring/Hibernate 响应中的属性为空

spring - 如何使用 Kotlin 正确查询 Spring JPA 中的实体

python - "RuntimeError: thread.__init__() not called"子类化 threading.Thread 时