Springboot多租户不适用于多线程

Springboot Multi-tenancy does not work with multi-threading

我已经引用了这个 link 来为两个数据源实现 springboot 多租户 - 不同的数据库(虽然相同的模式) - https://anakiou.blogspot.in/2015/08/multi-tenant-application-with-spring.html

在我没有在我的应用程序中引入任何多线程之前它工作正常。

当我添加一个 ExecutorService 来为 csv 文件中的每条记录在多个表中插入时 - 我看到新线程不包含进行其余服务调用的原始租户标识符的信息。

相反,它开始在新线程中使用默认租户。

我们如何解决这个问题?非常感谢任何指点。

编辑 1:ExecutorService 代码:尝试如下设置当前租户:

List<Future<Output>> futures = new ArrayList<Future<Output>>();
        for (int j = 0; j < myList.size(); j++) {

            final Output output= myList.get(j);

            Future<Output> future = executorService.submit(new Callable<Output>() {
                @Override
                public Output call() throws Exception {
                    **TenantContext.setCurrentTenant(<current tenant goes here>);**
                    Output currentOutput= someService.executeQueries(output);
                    return currentOutput;
                }
            });
            futures.add(future);
        }

传播租户的正常方法是使用 ThreadLocals。在博客示例中,它使用 class RequestContextHolder 将整个请求存储在 ThreadLocal 中,然后从那里解析租户。

当您更改线程时,线程局部变量将在新线程中丢失,除非您重新设置它们。