ThreadLocalHolder 工具类
public class ThreadLocalHolder {
private static ThreadLocal<User> userThreadLocal = new ThreadLocal<>();
public static void setUserLocal(User user) {
userThreadLocal.set(user);
}
public static void removeUserLocal() {
userThreadLocal.set(null);
userThreadLocal.remove();
}
public static void remove() {
removeUserLocal();
}
public static void main(String[] args) throws InterruptedException {
List<Thread> threadList = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
int finalI = i;
Thread thread = new Thread(() -> {
setUserLocal(new User("name" + finalI, "P" + finalI, Collections.singleton(new JaasGrantedAuthority("a", null))));
System.out.println(JSON.toJSON(userThreadLocal.get()));
});
thread.start();
remove();
threadList.add(thread);
}
for (Thread t : threadList) {
//等所有线程执行完成后才执行 "开始执行!!!!!!"
t.join();
}
System.out.println("开始执行!!!!!!");
}
}
通过objectMapper反射
@Slf4j
public class RobotUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
}
/**
* @Description: json串转换为指定类型对象
* @param <T>
* @param json
* @param type
* @return T
*/
public static <T> T jsonToBean(String json, TypeReference<T> type) {
try {
return objectMapper.readValue(json, type);
} catch (IOException e) {
log.error("数据:" + json + ",反序列化失败,类型:" + type.getType(), e);
throw new CommonException(CommonExceptionEnum.JSON_DESERIALIZE_EXCEPTION.getCode(), json);
}
}
/**
* @Description: bean转换为json串
* @param <T>
* @param bean
* @return String
*/
public static <T> String beanToJson(T bean) {
try {
return objectMapper.writeValueAsString(bean);
} catch (JsonProcessingException e) {
log.error("序列化失败,类型:" + bean.toString(), e);
throw new CommonException(CommonExceptionEnum.BEAN_SERIALIZE_EXCEPTION.getCode(), bean.toString());
}
}
}