2024-04-27 17:51:47 +08:00
|
|
|
package com.zhgd.xmgl.util;
|
|
|
|
|
|
|
|
|
|
import com.alibaba.fastjson.JSONObject;
|
|
|
|
|
|
|
|
|
|
public class ThreadLocalUtil {
|
|
|
|
|
|
2024-05-31 11:45:33 +08:00
|
|
|
private static final ThreadLocal<JSONObject> threadLocal = new ThreadLocal<>();
|
|
|
|
|
|
2024-04-27 17:51:47 +08:00
|
|
|
private ThreadLocalUtil() {
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void set(JSONObject str) {
|
|
|
|
|
threadLocal.set(str);
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-31 11:45:33 +08:00
|
|
|
public static JSONObject get() {
|
|
|
|
|
return threadLocal.get();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static JSONObject getNotNull() {
|
|
|
|
|
if (get() == null) {
|
|
|
|
|
threadLocal.set(new JSONObject());
|
|
|
|
|
}
|
|
|
|
|
return get();
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-01 14:37:49 +08:00
|
|
|
public static <T> T getByKey(String key, Class<T> clz) {
|
2024-05-31 11:45:33 +08:00
|
|
|
if (get() == null) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
2024-06-01 14:37:49 +08:00
|
|
|
return (T) get().get(key);
|
2024-05-31 11:45:33 +08:00
|
|
|
}
|
|
|
|
|
|
2024-04-27 17:51:47 +08:00
|
|
|
public static void add(JSONObject str) {
|
|
|
|
|
if (get() == null) {
|
|
|
|
|
threadLocal.set(str);
|
|
|
|
|
} else {
|
|
|
|
|
get().putAll(str); // 合并两个JSONObject
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void addInKey(String key, Object val) {
|
|
|
|
|
JSONObject jo = new JSONObject();
|
|
|
|
|
jo.put(key, val);
|
|
|
|
|
add(jo);
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-31 11:45:33 +08:00
|
|
|
public static void addInKeyIfNotExist(String key, Object val) {
|
|
|
|
|
JSONObject jo = getNotNull();
|
|
|
|
|
if (!jo.containsKey(key)) {
|
|
|
|
|
jo = new JSONObject();
|
|
|
|
|
jo.put(key, val);
|
|
|
|
|
add(jo);
|
2024-04-27 17:51:47 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void remove() {
|
|
|
|
|
threadLocal.remove();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
JSONObject jo = new JSONObject();
|
|
|
|
|
jo.put("jo", "0");
|
|
|
|
|
set(jo);
|
|
|
|
|
System.out.println(threadLocal.get());
|
|
|
|
|
JSONObject jo1 = new JSONObject();
|
|
|
|
|
jo1.put("jo1", "1");
|
|
|
|
|
set(jo1);
|
|
|
|
|
System.out.println(threadLocal.get());
|
|
|
|
|
JSONObject jo2 = new JSONObject();
|
|
|
|
|
jo2.put("jo2", "2");
|
|
|
|
|
add(jo2);
|
|
|
|
|
System.out.println(threadLocal.get());
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|