2016-11-05 3 views
2

스프링 부트를 사용 중이며 하나의 비동기 메소드가 있습니다. 비동기를 실행하려면 다음과 같은 구성이 필요합니다. 어떤 이유로 든 5 개의 스레드가 멈 추면 본질적으로 응용 프로그램을 잠그고 새 작업이 실행되지 않습니다 (그대로 받아들입니다). 우리가 작업 쓰레드에 대한 타임 아웃을 설정하는 방법은 120 초가 걸리므로 타임 아웃 후 새로운 태스크를 실행하십시오. timed라는 새로운 콩을 만든 다음스레드 풀에 대한 스레드 풀 실행 프로그램 시간 초과

static class TimeOutExecutorService extends CompletableExecutors.DelegatingCompletableExecutorService { 
    private final Duration timeout; 
    private final ScheduledExecutorService schedulerExecutor; 

    TimeOutExecutorService(ExecutorService delegate, Duration timeout) { 
     super(delegate); 
     this.timeout = timeout; 
     schedulerExecutor = Executors.newScheduledThreadPool(1); 
    } 

    @Override public <T> CompletableFuture<T> submit(Callable<T> task) { 
     CompletableFuture<T> cf = new CompletableFuture<>(); 
     Future<?> future = delegate.submit(() -> { 
      try { 
       cf.complete(task.call()); 
      } catch (CancellationException e) { 
       cf.cancel(true); 
      } catch (Throwable ex) { 
       cf.completeExceptionally(ex); 
      } 
     }); 

     schedulerExecutor.schedule(() -> { 
      if (!cf.isDone()) { 
       cf.completeExceptionally(new TimeoutException("Timeout after " + timeout)); 
       future.cancel(true); 
      } 
     }, timeout.toMillis(), TimeUnit.MILLISECONDS); 
     return cf; 
    } 
} 

: 당신이 좋아하는 다른 실행기를 만들 수 있습니다

@EnableAsync 
@Configuration 
public class AsyncConfiguration implements AsyncConfigurer { 

@Override 
public Executor getAsyncExecutor() { 
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); 
    taskExecutor.setCorePoolSize(5); 
    taskExecutor.setMaxPoolSize(5); 
    taskExecutor.initialize(); 
    return taskExecutor; 
} 

@Override 
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 
    return new SimpleAsyncUncaughtExceptionHandler(); 
} 

}

+0

답변이 필요합니다. – user3444718

+0

이것을 시도하십시오 :'taskExecutor.setKeepAliveSeconds (120)' –

+0

사함, 응답 주셔서 감사하지만 그 의미가 다릅니다. 이 usecause를 위해 작동하지 않을 것이다. (http://stackoverflow.com/questions/10379314/how-does-keep-alive-work-with-threadpoolexecutor) – user3444718

답변

0

을 (그래, 난 받아들이는 작업을 계속 바운드 형식의 큐와 고정 스레드 풀을 사용하고 있습니다)

@Bean(name = "timed") 
public Executor timeoutExecutor() { 
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("timed-%d").build(); 
    return TimedCompletables.timed(Executors.newFixedThreadPool(10, threadFactory), Duration.ofSeconds(2)); 
} 

그리고이 Executor을 사용해보십시오. 비동기 작업.

또는 FixSizeThreadPool에서 코드를 변경하여 고유 한 스레드 풀 실행 프로그램을 작성하십시오.