org.macrocloud.kernel.context.ServletContext Maven / Gradle / Ivy
package org.macrocloud.kernel.context;
import lombok.RequiredArgsConstructor;
import org.macrocloud.kernel.context.props.BaseContextProperties;
import org.macrocloud.kernel.toolkit.utils.StringUtil;
import org.macrocloud.kernel.toolkit.utils.ThreadLocalUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import java.util.function.Function;
import static org.macrocloud.kernel.toolkit.constant.BaseConstant.CONTEXT_KEY;
/**
* servlet 上下文,跨线程失效
*/
@RequiredArgsConstructor
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class ServletContext implements BaseContext {
private final BaseContextProperties contextProperties;
private final HttpHeadersGetter httpHeadersGetter;
@Nullable
@Override
public String getRequestId() {
return get(contextProperties.getHeaders().getRequestId());
}
@Nullable
@Override
public String getAccountId() {
return get(contextProperties.getHeaders().getAccountId());
}
@Nullable
@Override
public String getTenantId() {
return get(contextProperties.getHeaders().getTenantId());
}
@Nullable
@Override
public String get(String ctxKey) {
HttpHeaders headers = ThreadLocalUtil.getIfAbsent(CONTEXT_KEY, httpHeadersGetter::get);
if (headers == null || headers.isEmpty()) {
return null;
}
return headers.getFirst(ctxKey);
}
@Nullable
@Override
public T get(String ctxKey, Function function) {
String ctxValue = get(ctxKey);
if (StringUtil.isBlank(ctxValue)) {
return null;
}
return function.apply(ctxKey);
}
}