zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
    

      

  • 相关阅读:
    view上面 长view时候要设置其frame的,
    controller.allowsEditing = NO;神医,
    怎样计算,遗留,
    编码,一点阅读(转:阮一峰的网络日志),
    原来 ascll是对英文系统的编码,
    CoreGraphics 画图,(转燕羽天空)
    Core Graphics,
    计算数据类型占有 字节的长度,
    浅谈Promise(一)
    原生js实现表格内容增删改
  • 原文地址:https://www.cnblogs.com/otways/p/12053520.html
Copyright © 2011-2022 走看看