[Java] ์๋ฐ ๋ฉํฐ์ฐ๋ ๋์์ ๋ก๊ทธํ์ธ์ ์ํ uuid ์ค์ ํ๊ธฐ
๋น๋๊ธฐ ์ฒ๋ฆฌ์ ๋ก๊น uuid ์ค์
ํธ๋ํฝ์ด ๋ง์ ํ๊ฒฝ์์ ๋ฉํฐ์ฐ๋ ๋๋ก ์์ ์ ์ฒ๋ฆฌํ๊ณ ์๋๋ฐ ๊ฐ ์ฐ๋ ๋์ uuid ์ค์ ์ด ์๋์ด ์์ด ๋ก๊ทธ์์ผ๋ก ํ์ธ์ด ๋ถ๊ฐํ ๊ฒฝ์ฐ๊ฐ ์๊ฒผ๋ค. ๊ธฐ์กด์๋ ์ ๋๊ณ ์์๋ ๊ฒ์ด์๊ณ ๋ญ๊ฐ ์์ ์์ ์ ํ๋ฉด์ ๋นผ๋จ๋ฆฐ ๊ฒ ๊ฐ์ ๋ค๋ฅธ ์ฐ๋ ๋๋ค์ ์ค์ ์ ๋ณด๋ค๊ฐ TaskDecorator๋ฅผ ๋ณด๊ฒ ๋์๋ค.
package com.keichee;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import java.util.Map;
public class LoggingTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable task) {
Map<String, String> callerThreadContext = MDC.getCopyOfContextMap();
return () -> {
MDC.setContextMap(callerThreadContext);
task.run();
};
}
}
LoggingTaskDecorator๋ TaskDecorator๋ฅผ ๊ตฌํํ๊ณ ์๋๋ฐ decorate(Runnable task) ๋ฉ์๋๋ง ๊ตฌํํด์ฃผ๋ฉด ๋๋ค.
์ฌ๊ธฐ์ TaskDecorator๋ ์ด๋ค task(์์ )์ ๊พธ๋ฉฐ์ค๋ค๋ ์๋ฏธ๋ก ์ง์ด์ง ์ด๋ฆ์ด๋ฉฐ ์คํ๋ง์ ์ฝ์ด ํจํค์ง์ ๋ค์ด์์ ๋งํผ ์์ฃผ ์ฌ์ฉ๋๋ ๋ ์์ด๋ผ๊ณ ์๊ฐํ๋ฉด ๋๋ค. ์คํ๋ง ๊ณต์ ๋ฌธ์์ ๋ฐ๋ฅด๋ฉด TaskDecorator๋ ์๋์ ๊ฐ์ด ์ค๋ช ์ด ๋์ด์๋ค.
A callback interface for a decorator to be applied to any Runnable about to be executed.
Note that such a decorator is not necessarily being applied to the user-supplied Runnable/Callable but rather to the actual execution callback (which may be a wrapper around the user-supplied task).
The primary use case is to set some execution context around the task's invocation, or to provide some monitoring/statistics for task execution.
Since:4.3
์, ๊ทธ๋ผ TaskDecorator๋ฅผ ๊ตฌํํ ์ด LoggingTaskDecorator๋ ์ด๋ป๊ฒ ์ฌ์ฉํ ๊น?
๊ฐ๋จํ๋ค. ์คํ๋ง์์ ์ ๊ณตํ๋ ThreadPoolTaskExecutor๋ฅผ ์ฌ์ฉํ๋ค๋ฉด setTaskDecorator() ๋ฉ์๋๋ฅผ ์ด์ฉํด ์ธํ ํด์ฃผ๊ธฐ๋ง ํ๋ฉด ๋๋ค.
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
t.setTaskDecorator(new LoggingTaskDecorator());
return t;
}