【问题标题】:How pass context in multithreading threading如何在多线程线程中传递上下文
【发布时间】:2019-02-22 21:45:23
【问题描述】:

我们使用多线程,需要每个子线程中调用线程的上下文。我们使用的是 Spring 4.3。

例如:

final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

CompletableFuture.supplyAsync(() -> {
    ...
    try {
        // take the security context from the caller
        SecurityContextHolder.getContext().setAuthentication(authentication);
        doOperations()

这种方法适用于安全上下文。它从调用者线程(rest 端点)传递,并将其传递给每个创建的可完成未来。

在调用链中的给定类中,我有以下构造:

@Context
protected ProvisioningContext provisioningContext;  
@Context
protected UriInfo uriInfo;

如何在新创建的线程中正确传递所有上下文?

ThreadContext.getContext() 之类的方法不起作用。

【问题讨论】:

    标签: java multithreading jax-rs


    【解决方案1】:

    您可以尝试实现类似于我在此处描述的内容

    Customize/Extend Spring's @Async support for shiro

    即:

    • 使用Spring的@Async注解在不同的线程中执行任务
    • 实现自定义ThreadPoolTaskExecutor,将当前上下文与要执行的任务相关联
    • 通过实现AsyncConfigurer 让 spring 使用这个任务执行器

    如果您想使用CompletableFuture.supplyAsync 之类的东西或本地执行器服务,与上面概述的方法相比,您最终会得到大量重复的代码 - 使用由 spring 管理的线程池。

    特别是对于像身份验证上下文这样的东西,从线程中删除上下文也很重要。否则,如果上下文被回收为执行器服务以执行另一个任务,则上下文可能仍会附加到线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 2017-11-15
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      相关资源
      最近更新 更多