๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ์‹œ ๋กœ๊น… 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๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ์„ค๋ช…์ด ๋˜์–ด์žˆ๋‹ค.

 

Functional Interface : This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.@FunctionalInterface public interface 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;
}