• 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);
            }
        }
    }
    

      

  • 相关阅读:
    DAG:区块链行业下一个引爆点?
    php7的新特性
    Linux中的冷热页机制概述
    撰写后台需求文档需要注意的那些事儿
    poj 1201 Intervals
    poj 1364
    poj Candies
    hdu 1429
    poj A Round Peg in a Ground Hole
    poj 1113Wall
  • 原文地址:https://www.cnblogs.com/otways/p/12053520.html
Copyright © 2020-2023  润新知