问题描述
示例:
MacBook-Air-alkhas-b-rjayy:new app 19:2 rjayy$ cd my-app
MacBook-Air-alkhas-b-rjayy:my-app rjayy$ npm start
> my-app@0.1.0 start /Users/rjayy/Desktop/react/my-app/src/new app 19:2/my-app
> react-scripts start
sh: react-scripts: command not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! my-app@0.1.0 start: `react-scripts start`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the my-app@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/rjayy/.npm/_logs/2021-03-09T17_37_55_559Z-debug.log
MacBook-Air-alkhas-b-rjayy:my-app rjayy$
由于 public class Controller {
@GET
public void requestController() {
// set user data in the controller currentThread
}
}
public class Service {
public void serviceMethod() {
// get user data in the service method from currentThread
}
}
和 Controller
在同一个线程中,我应该能够访问 Service
中设置的 Service
中的对象。
Controller
确实使用 MDC
和 MDC.put
遵循相同的方法,但我不确定它使用哪种模式。
解决方法
您正在寻找ThreadLocal。 MDC 在内部使用它。
用法
用法很简单。您需要一个 ThreadLocal 实例,所有需要访问它的组件都可以访问该实例。在大多数情况下,它只是一个 public static final
变量。
public class SomeClass {
// use whatever class you want here,String for example
public static final ThreadLocal<String> TL_MESSAGE = new ThreadLocal<>();
}
public class Controller {
@GET
public void requestController() {
SomeClass.TL_MESSAGE.set("hello world");
try {
// everything after set should be wrapped in this try-finally-block
service.serviceMethod();// this can be anywhere in the code,it doesnt have to called here directly. As long as the thread is the same and the method is called between set and remove
} finally {
SomeClass.TL_MESSAGE.remove();
}
}
}
public class Service {
public void serviceMethod() {
String message = SomeClass.TL_MESSAGE.get();
}
}
陷阱/内存泄漏可能性!
确保始终删除您设置的值。 有关详细信息,请参阅:ThreadLocal & Memory Leak