CurrentUser.java 2.41 KB
package com.dituhui.pea.pojo;

import brave.Tags;
import brave.Tracer;
import brave.baggage.BaggageField;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 当前用户类
 * @author dk
 */
@Component
public class CurrentUser {

    @Autowired
    Tracer tracer;

    /**
     * 当前线程用户信息
     */
    public static ThreadLocal<PlatformUser> threadPlatformUser = new ThreadLocal<PlatformUser>();

    /**
     * 创建当前线程对应的用户
     *
     * @return
     */
    private PlatformUser createPlatformUser() {
        // 如果没有用户信息则创建
        PlatformUser user = new PlatformUser();
        String tagTrace = this.tracer.currentSpan().context().traceIdString();
        if (StringUtils.isNotEmpty(tagTrace)) {
            user.setIdLog(tagTrace);
        }
        String tagToken = getBaggageFieldValue("token");
        if (StringUtils.isNotEmpty(tagToken)) {
            user.setToken(tagToken);
        }
        String tagClientIp = getBaggageFieldValue("clientIp");
        if (StringUtils.isNotEmpty(tagClientIp)) {
            user.setClientIP(tagClientIp);
        }
        user.setUserId(getBaggageFieldValue("userId"));
        user.setTeamId(getBaggageFieldValue("teamId"));
        user.setT(getBaggageFieldValue("t"));
        return user;
    }

    /**
     * 获取用户请求标签
     *
     * @param name 参数名称
     * @return
     */
    private String getBaggageFieldValue(String name) {
        BaggageField baggageField = BaggageField.create(name);
        return Tags.BAGGAGE_FIELD.value(baggageField, this.tracer.currentSpan().context());
    }

    /**
     * 获取 用户信息
     *
     * @return 用户信息
     */
    public PlatformUser getPlatformUser() {
        PlatformUser platformUser = threadPlatformUser.get();
        if (null == platformUser || StringUtils.isEmpty(platformUser.getUserId())) {
            platformUser = createPlatformUser();
            threadPlatformUser.set(platformUser);
        }
        return platformUser;
    }

    /**
     * 设置 用户信息
     *
     * @param user 用户信息
     */
    public void setPlatformUser(PlatformUser user) {
        threadPlatformUser.set(user);
    }

    /**
     * 移除当前线程用户
     */
    public void removePlatformUser() {
        threadPlatformUser.remove();
    }

}