ThreadLocalUtil

2024-01-04 08:20:29 浏览数 (1)

代码语言:javascript复制
import lombok.Getter;

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

public class ThreadLocalUtil {

    private static final ThreadLocal<Map<ThreadLocalUtil.Key, Object>> CACHE = new ThreadLocal<Map<ThreadLocalUtil.Key, Object>>() {
        protected Map<ThreadLocalUtil.Key, Object> initialValue() {
            return new HashMap();
        }
    };

    public ThreadLocalUtil() {
    }

    public static Object put(String key, Object value) {
        return ((Map)CACHE.get()).put(key, value);
    }

    public static Object get(String key) {
        return ((Map)CACHE.get()).get(key);
    }

    public static <T> T get(String key, Class<T> valueClass) {
        return valueClass.cast(get(key));
    }

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

    public static void clear() {
        ((Map)CACHE.get()).clear();
    }


    @Getter
    public static enum Key {
        ENABLE_POOLING;

        public static String getKey(String str) {
            Thread thread = Thread.currentThread();
            return thread   "_"   str;
        }
    }

}

代码语言:javascript复制
ThreadLocalUtil.put(ThreadLocalUtil.Key.getKey(siteOrderNo),salesOrdersFetch);

  记得使用

代码语言:javascript复制
ThreadLocalUtil.remove();

0 人点赞