如何解决如何使用线程上下文跨方法传递对象?
示例:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。