[Spring Boot] @Async 사용해보기

exoluse·2021년 12월 20일
1

Spring

목록 보기
9/11
post-thumbnail

AsyncConfig

package com.iut.mes.config;

import java.util.concurrent.Executor;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class AsyncConfig extends AsyncConfigurerSupport {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(16);
        executor.setQueueCapacity(5000);
        executor.setThreadNamePrefix("iut-mes-async-work");
        executor.initialize();
        return executor;
    }
}

AsyncController

package com.iut.mes.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.iut.mes.service.AsyncService;

@RestController
public class AsyncController {

    Logger logger = LoggerFactory.getLogger(AsyncController.class);

    @Autowired
    AsyncService asyncService;

    @Autowired
    private AsyncService service;

    @GetMapping("/startAsync")
    public String startAsync() {
        service.startAsync();
        String str = "Async!!";
        logger.info(str);
        return str;
    }

    @GetMapping("/startSync")
    public String startSync() {
        service.startSync();
        String str = "Sync!!";
        logger.info(str);
        return str;
    }

}

AsyncService

package com.iut.mes.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    private static final Logger logger = LoggerFactory.getLogger(AsyncService.class);

    //비동기로 동작하는 메소드
    @Async
    public void startAsync() {
        try {
            Thread.sleep(5000);
            logger.info("startAsync");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //동기로 동작하는 메소드
    public void startSync() {
        try {
            Thread.sleep(5000);
            logger.info("startSync");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

쓰임새

파일 업로드, 로그 적재, 그 외 순서 상관없는 백그라운드 처리가 필요한 작업들

0개의 댓글