Java -- TransmittableThreadLocal使用

背景:

        项目添加了登录模块,用户信息保存到上下文中,使用TransmittableThreadLocal,这样在业务层就可以直接拿到用户信息

操作:

        导入依赖:

            
                com.alibaba
                transmittable-thread-local
                2.12.2
            

        工具类:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.ttl.TransmittableThreadLocal;


public class SecurityContextHolder
{
    private static final TransmittableThreadLocal> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value)
    {
        Map map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }

    public static String get(String key)
    {
        Map map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
    }

    public static  T get(String key, Class clazz)
    {
        Map map = getLocalMap();
        return StringUtils.cast(map.getOrDefault(key, null));
    }

    public static Map getLocalMap()
    {
        Map map = THREAD_LOCAL.get();
        if (map == null)
        {
            map = new ConcurrentHashMap();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map threadLocalMap)
    {
        THREAD_LOCAL.set(threadLocalMap);
    }

    public static void remove()
    {
        THREAD_LOCAL.remove();
    }
}

        在拦截器里面添加用户信息:

        SecurityContextHolder.set("userId",userId);
        SecurityContextHolder.set("userName",userName);

        业务层里获取用户信息:

        SecurityContextHolder.get("userId");
        SecurityContextHolder.get("userName");

你可能感兴趣的:(java,服务器)