이전 블로그 인 http://www.vevb.com/article/106718.htm에서는 Spring Boot의 비동기 조작을 사용했습니다. 당시 우리는 기본 스레드 풀을 사용했지만 프로젝트에 따라 자체 스레드 풀을 사용자 정의하려면 스레드 풀을 사용자 정의하는 방법에 대해 이야기 해 봅시다!
패키지 com.chhliu.springboot.async.configuration; org.springframework.boot.context.properties.configurationProperties; @ConfigurationProperties (prefix = "spring.task.pool") //이 주석의 위치가 활성화되었습니다. 이제 환경에있는 한, 공개 클래스 TaskthreadPoolConfig {private int corepoolsize; 개인 int maxpoolsize; 개인 int keepaliveseconds; 개인 queuecapacity; ……… getter를 생략, 세터 방법 ………} 패키지 com.chhliu.springboot.async.pool; import java.util.concurrent.executor; java.util.concurrent.threadpoolexecutor import; org.springframework.beans.factory.annotation.autowired; import org.springframework.context.annotation.bean; org.springframework.context.annotation.configuration; org.springframework.scheduling.annotation.enableasync; org.springframework.scheduling.concurrent.threadpooltaskexecutor; com.chhliu.springboot.async.configuration.taskthreadpoolconfig; @configuration @enableAsync public class taskexecutepool {@autowired private taskthreadpoolconfig config; @Bean 공개 집행자 MyTaskAsyncPool () {ThreadPooltasKexeCutor Executor = New ThreadPoolTaskexEcutor (); executor.setCorePoolSize (config.getCorePoolSize ()); executor.setMaxPoolSize (config.getMaxPoolSize ()); executor.setqueuecapacity (config.getqueuecapacity ()); Executor.setKeepaliveseconds (config.getKeepaliveseconds ()); executor.setthreadnameprefix ( "myExecutor-"); // Rejection-Policy : 풀이 최대 크기에 도달했을 때 새 작업을 처리하는 방법 // caller_runs : 새 스레드에서 작업을 실행하지 말고 Executor.setRecedExecutionHandler (new ThreadPooleExecutor.callerRunspolicy ())를 실행하십시오. executor.initialize (); 귀환 집행자; }} 패키지 com.chhliu.springboot.async; org.springframework.boot.springApplication import; org.springframework.boot.autoconfigure.springbootapplication import; org.springframework.boot.context.properties.enableconfigurationProperties; org.springframework.scheduling.annotation.enableasync; com.chhliu.springboot.async.configuration.taskthreadpoolconfig; @SpringBootApplication @enableAsync @enableConfigurationProperTies ({taskthreadpoolconfig.class}) // 공개 클래스를 지원하기위한 구성 속성 활성화 SpringBootAsynCapplication {public static void main (String [] args) {SpringBootSyncapplication.class, Args); }} 패키지 com.chhliu.springboot.async.pool; import org.slf4j.logger; org.slf4j.loggerfactory; import org.springframework.scheduling.annotation.async; org.springframework.stereotyp.component import; @component public class asynctask {보호 된 최종 로거 로거 = loggerfactory.getLogger (this.getClass ()); @async ( "mytaskasyncpool") // mytaskasyncpool은 스레드 풀을 구성하는 메소드 이름입니다. 여기에 사용자 정의 스레드 풀의 메소드 이름을 쓰지 않으면 기본 스레드 풀이 공개 void dotask1 (int i)을 사용합니다. InterruptedException {logger.info ( "task"+i+"start."); }} 패키지 com.chhliu.springboot.async; import java.util.concurrent.executionException; import org.junit.test; import org.junit.runner.runwith; import org.slf4j.logger; org.slf4j.loggerfactory; org.springframework.beans.factory.annotation.autowired; org.springframework.boot.test.context.springboottest; org.springframework.test.context.junit4.springrunner import; com.chhliu.springboot.async.pool.asynctask import; @RunWith (SpringRunner.class) @SpringBoottest 공개 클래스 SpringBootasyNCapplicationTests {Protected Final Logger = LoggerFactory.getLogger (this.getClass ()); @autowired Private Asynctask Asynctask; @test public void asynctasktest ()는 InterruptedException, executionException {for (int i = 0; i <100; i ++) {asynctask.dotask1 (i); } logger.info ( "모든 작업이 완료되었습니다."); }} 테스트 결과는 다음과 같습니다.
2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-10] ccspringboot.async.pool.asynctask : task60 시작. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-25] ccspringboot.async.pool.asynctask : task61이 시작되었습니다. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-6] ccspringboot.async.pool.asynctask : task62 시작되었습니다. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-23] ccspringboot.async.pool.asynctask : task63 시작. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-20] ccspringboot.async.pool.asynctask : task64 시작. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-19] CCSpringBoot.async.pool.asynctask : task65가 시작되었습니다. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-16] ccspringboot.async.pool.asynctask : task66 시작. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-15] CCSpringBoot.async.pool.asynctask : task67이 시작되었습니다. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-15] CCSpringBoot.async.pool.asynctask : task67이 시작되었습니다. 2017-03-20 20 : 15 : 15.208 Info 4068 --- [MyExecutor-12] ccspringboot.async.pool.asynctask : task68이 시작되었습니다. 2017-03-20 20 : 15 : 15.209 Info 4068 --- [MyExecutor-1] ccspringboot.async.pool.asynctask : task69가 시작되었습니다. 2017-03-20 20 : 15 : 15.209 Info 4068 --- [MyExecutor-11] ccspringboot.async.pool.asynctask : task81이 시작되었습니다. 2017-03-20 20 : 15 : 15.209 Info 4068 --- [MyExecutor-8] ccspringboot.async.pool.asynctask : task82가 시작되었습니다. 2017-03-20 20 : 15 : 15.209 Info 4068 --- [MyExecutor-7] ccspringboot.async.pool.asynctask : task83이 시작되었습니다. 2017-03-20 20 : 15 : 15.209 Info 4068 --- [MyExecutor-4] ccspringboot.async.pool.asynctask : task84가 시작되었습니다. 2017-03-20 20 : 15 : 15.209 Info 4068 --- [MyExecutor-29] ccspringboot.async.pool.asynctask : task85가 시작되었습니다. 2017-03-20 20 : 15 : 15.209 Info 4068 --- [MyExecutor-21] ccspringboot.async.pool.asynctask : task86이 시작되었습니다. 2017-03-20 20 : 15 : 15.209 Info 4068 --- [MyExecutor-17] ccspringboot.async.pool.asynctask : task88이 시작되었습니다.
테스트 결과는 괜찮습니다!
기본 스레드 풀을 사용하려면 기본 스레드 풀의 구성을 수정하려면 어떻게해야합니까? 현재 AsyncConfigurer 클래스를 구현해야합니다. 샘플 코드는 다음과 같습니다.
import java.lang.reflect.method; import java.util.concurrent.executor; java.util.concurrent.threadpoolexecutor import; org.springframework.aop.interceptor.asyncuncaughtexceptionhandler import; org.springframework.beans.factory.annotation.autowired; org.springframework.context.annotation.configuration; org.springframework.scheduling.annotation.asyncconfigurer; org.springframework.scheduling.concurrent.threadpooltaskexecutor; com.chhliu.cq.emailservice.threadconfiguration.taskthreadpoolconfig import; 가져 오기 lombok.extern.slf4j.slf4j; / ** * 참고 :이 스레드 풀은 모든 비동기식 작업에 의해 공유되며 특정 비동기 작업에 속하지 않습니다 * 설명 : 비동기 작업 구성을위한 스레드 풀 * @Author chhliu * 생성 시간 : 2017 년 5 월 22 일 오전 1.2.0 */ @slf4j @configuration public classes Asyncutepool Implements Public Classe asyncconfigurer {@autowired private taskthreadpoolconfig config; // 속성 클래스를 구성하려면 위의 코드를 참조하십시오. @Override public executor getAsyncexecutor () {ThreadPooltasKexEcutor Executor = new ThreadPoolTasKexEcutor (); executor.setCorePoolSize (config.getCorePoolSize ()); executor.setMaxPoolSize (config.getMaxPoolSize ()); executor.setqueuecapacity (config.getqueuecapacity ()); Executor.setKeepaliveseconds (config.getKeepaliveseconds ()); executor.setThreadnamEprefix ( "taskexecutor-"); // 거부 폴리니 : 풀이 최대 크기에 도달했을 때 새 작업을 처리하는 방법 // caller_runs : 작업은 새 스레드에서 실행되지 않지만 발신자가 위치한 스레드가 실행자를 실행합니다. executor.initialize (); 귀환 집행자; } @override public asyncuncuggexceptionHandler getAsyncuncuggexceptionHandler () {// 비동기 작업에서의 예외 처리를 반환합니다. 로러 ( "==================================================================================================================================== ================================================================= =================================================================== ================================================================= =================================================================== ================================================================= =================================================================== 그것을 사용할 때는 메소드에 @async를 추가하십시오.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.