VrApiContext.java 2.17 KB
package com.glsx.usedcar.context;

import com.glsx.usedcar.module.inspect.entity.Inspector;
import lombok.extern.slf4j.Slf4j;

/**
 * 检测师上下文对象
 */
@Slf4j
public class VrApiContext {
    /**
     * 存储当前线程的用户信息,KEY 命名与存储内容匹配(原 USER_NAME_TL 命名不规范,已修正)
     */
    private static final ThreadLocal<Inspector> VR_TL = new ThreadLocal<>();

    /**
     * 保存用户信息到当前线程上下文
     *
     * @param user 用户信息DTO(允许传 null,代表无登录用户)
     */
    public static void saveVr(Inspector user) {
        if (user != null) {
            VR_TL.set(user);
        }
    }

    /**
     * 获取当前线程的用户信息
     *
     * @return 用户信息DTO(无登录用户时返回 null)
     */
    public static Inspector getInspector() {
        return VR_TL.get();
    }

    /**
     * 清除当前线程的用户信息(必须调用,防止 ThreadLocal 内存泄漏)
     */
    public static void removeInspector() {
        try {
            VR_TL.remove();
            log.debug("用户上下文已清除当前线程的用户信息");
        } catch (Exception e) {
            log.error("清除用户上下文失败", e);
        }
    }

    /**
     * 获取当前登录用户ID
     *
     * @return 检测师ID
     */
    public static Long getInspectorId() {
        Inspector inspector = getInspector();
        return inspector == null ? null : inspector.getId();
    }

    /**
     * 获取当前登录用户手机号(无登录用户返回 null)
     *
     * @return 用户手机号
     */
    public static String getPhone() {
        Inspector inspector = getInspector();
        return inspector == null ? null : inspector.getPhone();
    }

    /**
     * 判断当前线程是否有登录用户
     *
     * @return true-已登录,false-未登录
     */
    public static boolean hasLogin() {
        return getInspector() != null;
    }

    public static Object getInspectorName() {
        Inspector inspector = getInspector();
        if (inspector == null) {
            return "未登录用户";
        }
        return inspector.getName();
    }
}