Код: Выделить всё
@RestController
@RequestMapping("/hello")
@RequiredArgsConstructor
@Slf4j
public class HelloController {
private final HelloService helloService;
@GetMapping
public ResponseEntity hello() {
log.info("Received request in controller. Handled by thread: {}. Is Virtual Thread?: {}",
Thread.currentThread().getName(), Thread.currentThread().isVirtual());
helloService.hello();
return ResponseEntity.ok("Hello, World!");
}
}
< /code>
Это вызывает функцию уровня службы < /p>
@Service
@Slf4j
public class HelloService {
@Async
public CompletableFuture hello() {
log.info("HelloService called");
try {
// Simulate some processing
Thread.sleep(30000);
log.info("In Thread: {}", Thread.currentThread().getName());
log.info("Is Virtual Thread?: {}", Thread.currentThread().isVirtual());
log.info("Hello service completed");
} catch (InterruptedException e) {
log.error("Error in HelloService", e);
Thread.currentThread().interrupt();
}
return CompletableFuture.completedFuture(null);
}
}
< /code>
Async Config присутствует в собственном файле конфигурации < /p>
@Configuration
@EnableAsync
@RequiredArgsConstructor
public class AsyncConfig {
private final ThreadContextDecorator threadContextDecorator;
@Bean
public ConcurrentTaskExecutor taskExecutor() {
ThreadFactory threadFactory = Thread.ofVirtual()
.name("async-executor-", 0)
.factory();
Executor virtualThreadExecutor = task -> {
Runnable runnable = threadContextDecorator.decorate(task);
try (var executor = Executors.newThreadPerTaskExecutor(threadFactory)) {
executor.execute(runnable);
}
};
return new ConcurrentTaskExecutor(virtualThreadExecutor);
}
}
< /code>
im Создание декоратора задачи для добавления поддержки MDC < /p>
@Component
@Slf4j
public class ThreadContextDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
Map contextMap = MDC.getCopyOfContextMap();
return () -> {
try {
if (contextMap != null) {
MDC.setContextMap(contextMap);
}
log.info("Decorating Thread: {}", Thread.currentThread().getName());
runnable.run();
} finally {
// Clear the MDC context to prevent memory leaks
MDC.clear();
}
};
}
}
< /code>
Ниже приведены журналы от контроллера.[omcat-handler-0] Received request in controller. Handled by thread: tomcat-handler-0. Is Virtual Thread?: true
[sync-executor-0] Decorating Thread: async-executor-0
[sync-executor-0] HelloService called
[sync-executor-0] In Thread: async-executor-0
[sync-executor-0] Is Virtual Thread?: true
[sync-executor-0] Hello service completed
Подробнее здесь: https://stackoverflow.com/questions/796 ... annotation