package com.sw.mes.config;

import javax.annotation.Nonnull;

import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @Author: liru
 * @Date: 2024-02-03 23:27
 */
public class ContextDecorator implements TaskDecorator {
	@Override
	public Runnable decorate(@Nonnull Runnable runnable) {
		// 获取主线程中的请求信息
		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
		return () -> {
			try {
				// 将主线程的请求信息，设置到子线程中
				RequestContextHolder.setRequestAttributes(attributes);
				// 执行子线程
				runnable.run();
			} finally {
				// 线程结束，清空这些信息，否则可能造成内存泄漏
				RequestContextHolder.resetRequestAttributes();
			}
		};
	}
}
