Skip to content

transmittable-thread-local在使用mybatis-plus多租户插件和disruptor处理保存导入数据的时候获取不到保存的租户值 #732

@shenhaifish

Description

@shenhaifish

public void publish(List dataRecords) {
String tenantId = TenantContextHolder.getTenantId();
if (tenantId == null) {
throw new IllegalStateException("Tenant ID is not available in the current thread context.");
} else {
System.out.println("租户id: " + tenantId);
}
for (T record : dataRecords) {
long sequence = ringBuffer.next(); // 获取下一个序列
try {
DataRecordEvent event = ringBuffer.get(sequence);
event.setRecord(record); // 将记录设置到事件中
log.debug("Published record to sequence {}: {}", sequence, record);
} finally {
ringBuffer.publish(sequence); // 发布序列
}
}
}
这个地方仍然能够获取成功,但是在onEvent已经获取失败了
public static class DataRecordEventHandle implements EventHandler<DataRecordEvent> {
private final List batch = new ArrayList<>();

    @Override
    public void onEvent(DataRecordEvent<T> event, long sequence, boolean endOfBatch) {
        String tenantId = TenantContextHolder.getTenantId(); // 显式从事件中获取租户 ID
        if (tenantId == null) {
            throw new IllegalStateException("Tenant ID is missing in the event.");
        }
        try {
            T record = event.getRecord();
            if (record != null) {
                batch.add(record);
                log.debug("Added record to batch: {}", record);
            }

            if (batch.size() >= BATCH_SIZE || endOfBatch) {
                saveBatch(batch, BATCH_SIZE);
                batch.clear();
            }
        } catch (Exception e) {
            log.error("Excel导入时出现异常: {}", ExceptionUtil.getExceptionMessage(e));
        } finally {
            event.setRecord(null);
            TenantContextHolder.remove();
        }
    }
}
上面的onEvent方法无法获取到缓存的租户字段值,后续执行到租户插件配置的时候也无法获取
是需要配置什么别的吗,已经使用自定义的线程工厂
public class TtlThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
private final ThreadGroup group;

public TtlThreadFactory(String namePrefix) {
    this.namePrefix = namePrefix;
    this.group = Thread.currentThread().getThreadGroup();
}

@Override
public Thread newThread(Runnable r) {
    Runnable ttlRunnable = TtlRunnable.get(r, true);
    Thread thread = new Thread(group, ttlRunnable,
            namePrefix + "-thread-" + threadNumber.getAndIncrement(),
            0);
    thread.setDaemon(false);
    thread.setPriority(Thread.NORM_PRIORITY);
    return thread;
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions