ThreadLocal全局获取用户信息

本文介绍如何利用ThreadLocal在Java Spring环境中实现每个请求线程中全局存储和获取用户信息,通过创建保存用户信息的工具类以及设置拦截器来确保线程安全的用户上下文操作。
摘要由CSDN通过智能技术生成

每个请求都会对应一个线程,ThreadLocal就是这个线程使用过程中的一个变量,该变量为其所属线程所有,各个线程互不影响

保存用户信息的工具类

package com.ahies.zgstm.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 用于在应用内及应用间保存、传递执行上下文信息。
 *
 * @author LIU Fangran
 */
public class ExecutionContext {
    /**
     * 用于保存线程相关信息
     */
    transient static ThreadLocal<Map<String, String>> threadLocal = new ThreadLocal<Map<String, String>>();


    public static final String USER_ID = "userId";
    public static final String USER_NAME = "userName";
    public static final String LOGIN_NAME = "loginName";
    public static final String DEPT_ID = "deptId";
    public static final String TOKEN = "token";
    // session类型
    public static final String SESSION_TYPE = "sessionType";
    public static final String DEVELOPER = "developer";


    /**
     * 构造函数
     */
    public ExecutionContext() {
    }

    /**
     * 从 ThreadLocal中获取名值Map(不包含appCode)
     *
     * @return 名值Map
     */
    public static Map<String, String> getContextMap() {
        Map<String, String> map = threadLocal.get();
        return map;
    }

    /**
     * 从 ThreadLocal 获取名值Map
     *
     * @param contextMap 名值Map
     */
    public static void setContextMap(Map<String, String> contextMap) {
        threadLocal.set(contextMap);
    }

    /**
     * (获取键下的值.如果不存在,返回null;如果名值Map未初始化,也返回null) Get the value of key. Would
     * return null if context map hasn't been initialized.
     *
     * @param key 键
     * @return 键下的值
     */
    public static String get(String key) {
        Map<String, String> contextMap = getContextMap();
        if (contextMap == null) {
            return null;
        }
        return contextMap.get(key);
    }

    /**
     * (设置名值对。如果Map之前为null,则会被初始化) Put the key-value into the context map;
     * <p>
     * Initialize the map if the it doesn't exist.
     *
     * @param key   键
     * @param value 值
     * @return 之前的值
     */
    public static String put(String key, String value) {
        Map<String, String> contextMap = getContextMap();
        if (contextMap == null) {
            c
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值