如何在async线程中访问RequestContextHolder

callable包装

public class ContextAwareCallable implements Callable {
    private Callable task;
    private RequestAttributes context;

    public ContextAwareCallable(Callable task, RequestAttributes context) {
        this.task = task;
        this.context = context;
    }

    @Override
    public T call() throws Exception {
        if (context != null) {
            RequestContextHolder.setRequestAttributes(context);
        }

        try {
            return task.call();
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }
    }
}

threadpool包装

public class ContextAwarePoolExecutor extends ThreadPoolTaskExecutor {
    @Override
    public  Future submit(Callable task) {
        return super.submit(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes()));
    }

    @Override
    public  ListenableFuture submitListenable(Callable task) {
        return super.submitListenable(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes()));
    }
}

异步线程配置

@Configuration
public class ExecutorConfig extends AsyncConfigurerSupport {
    @Override
    @Bean
    public Executor getAsyncExecutor() {
        return new ContextAwarePoolExecutor();
    }
}

doc

  • How to enable request scope in async task executor


想获取最新内容,请关注微信公众号

如何在async线程中访问RequestContextHolder_第1张图片

你可能感兴趣的:(springboot)