threadlocal应用


public
class DataSourceSelector { /** * 线程threadlocal */ private static ThreadLocal<String> dbLookCxt = new ThreadLocal<>(); public static final String _DEFAULT_DB = MultiDruidDataSources.PREFIX+".default"; public static String getDataSourceKey() { String db = dbLookCxt.get(); if (db == null) { db = _DEFAULT_DB; } return db; } public static void select(String dbKey) { dbLookCxt.set(dbKey); } public static void remove() { dbLookCxt.remove(); } }

以及用于

public class TransactionContextHolder {

    public static final String TRACE_ID = "traceId";

    private static ThreadLocal<HashMap<String, String>> locals = new ThreadLocal<>();

    public static void set(HashMap<String, String> data){
        HashMap<String, String> map = locals.get();
        if (map == null) {
            locals.set(data);
        } else {
            map.putAll(data);
        }
        if (data.containsKey(TRACE_ID)) {
            String traceIdValue = data.get(TRACE_ID);
            MDC.put("traceId", traceIdValue);
        }

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

    public static void set(String key, String value){
        if (value != null && key != null){
            get().put(key, value);
            if (TRACE_ID.equals(key)) {
                MDC.put("traceId", value);
            }
        }
    }

    public static HashMap<String, String> get() {

        HashMap<String, String> map = locals.get();
        if (map == null) {
            map = new HashMap<>();
            set(map);
        }
        return map;
    }

    public static void remove(){
        locals.remove();
        MDC.remove("traceId");
    }

    public static void remove(String key) {
        get().remove(key);
    }

    public static void copy(Map<String, String> parentContext) {
        if (parentContext != null && parentContext.size() > 0) {
            get().putAll(parentContext);
        }
    }
}

  

原文地址:https://www.cnblogs.com/otways/p/12053520.html