Skip to content

idefav/magic-async-context

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

magic-aync-context

A magical Java thread pool that supports context transfer between threads or thread pools

Feature

  1. Support for Runable,Callable and thread pool wrappers
  2. Asynchronous thread context passing
  3. Support integration with other contexts or ThreadLocal

Main thread and child thread context merge logic

image 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.

Quick Start

  1. Import dependencies
<dependency>
  <groupId>com.idefav</groupId>
  <artifactId>magic-async-context</artifactId>
  <version>1.0.1</version>
</dependency>
  1. 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());
    }
  1. 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

About

A magical Java async context that supports context transfer between threads or thread pools.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages