A magical Java thread pool that supports context transfer between threads or thread pools
- Support for
Runable,Callableand thread pool wrappers - Asynchronous thread context passing
- Support integration with other contexts or ThreadLocal
The child thread merges the main thread context in the middle, the main thread context attribute will be automatically overwritten to the child thread, and the child thread context will be restored after the attach ends.
- Import dependencies
<dependency>
<groupId>com.idefav</groupId>
<artifactId>magic-async-context</artifactId>
<version>1.0.1</version>
</dependency>- Usage
- Context
// Set value in Context
Context.current().put("name", name);
// Get the value from the Context, you can get the value in the child thread
Context.current().get("name")- RequestContext
// First get the Context from the ServletContext and set it to the Context
RequestHolder.set((HttpServletRequest) request)
// Get RequestURI
RequestHolder.get().getRequestURI()- Demo
@GetMapping("/say/{name}")
public String say(@PathVariable("name") String name) throws InterruptedException {
Context.current().put("name", name);
executorService.submit(new Runnable() {
@Override
public void run() {
System.out.println(String.format("name: %s, requestUri:%s", Context.current()
.get("name"), RequestHolder.get().getRequestURI())); ;
}
});
Thread.sleep(10);
return String.format("hello, %s,RequestUri:%s", Context.current().get("name"), RequestHolder.get()
.getRequestURI());
}- Spring Boot Starter
<dependency>
<groupId>com.idefav</groupId>
<artifactId>magic-async-context-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency> Using Spring Boot Starter will automatically integrate RequestContext by default, you can directly use RequestHolder.get().getRequestURI to get request information