Created
January 16, 2017 14:57
-
-
Save yarosla/e1cfe46087a93c2fa3b0d8ec49595dd3 to your computer and use it in GitHub Desktop.
Spring Async demo for http://stackoverflow.com/q/41672364/697313
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ys | |
import groovy.util.logging.Slf4j | |
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler | |
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.context.annotation.Bean | |
import org.springframework.context.annotation.Configuration | |
import org.springframework.scheduling.annotation.* | |
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler | |
import org.springframework.test.context.ContextConfiguration | |
import spock.lang.Specification | |
import ys.AsyncSpec.SchedulingConfiguration | |
import java.util.concurrent.Executor | |
import java.util.concurrent.Future | |
@Slf4j | |
@ContextConfiguration(classes = [SchedulingConfiguration.class]) | |
class AsyncSpec extends Specification { | |
static final int VALUE = 111 | |
@Autowired | |
FooService fooService | |
def "test async"() { | |
setup: | |
Future<Integer> result = fooService.foo() | |
expect: | |
result.get() == VALUE | |
} | |
static class FooService { | |
@Async | |
Future<Integer> foo() { | |
log.info('foo invoked') | |
return new AsyncResult<Integer>(VALUE) | |
} | |
} | |
@EnableScheduling | |
@EnableAsync | |
@Configuration | |
static class SchedulingConfiguration implements AsyncConfigurer { | |
@Bean | |
FooService fooService() { | |
return new FooService() | |
} | |
@Override | |
Executor getAsyncExecutor() { | |
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler() | |
scheduler.setPoolSize(10) | |
scheduler.initialize() | |
return scheduler | |
} | |
@Override | |
AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { | |
return { e, method, params -> log.error("Async error in method {}", method, e) } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment