Java&Spring基础技术Java学习笔记

基于 Spring 的异步调用框架

2017-07-25  本文已影响161人  空之古城

Spring 异步调用框架提供了一套异步调用简化方式,只需要写几个注解就能完成调用方法从同步到异步的转化。

使用

Maven 依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.6.RELEASE</version>
</dependency>

代码实现

线程池配置代码:

@Service
@Configurable
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(7);
        executor.setMaxPoolSize(42);
        executor.setQueueCapacity(11);
        executor.setThreadNamePrefix("MyExecutor-");
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        System.out.println("AsyncDemoApp.getAsyncUncaughtExceptionHandler");
        return (throwable, method, objects) -> {
            System.out.println("handle uncaught exception");
            System.out.println(throwable);
        };
    }

}

异步方法实现:

@Component
public class AsyncJob {

    @Async
    public void asyncMethodWithVoidReturnType() {
        try {
            Thread.sleep(1000);
            throw new RuntimeException("hello world exception!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Execute method asynchronously. "
                + Thread.currentThread().getName());
    }

    @Async
    public Future<String> asyncMethodWithReturnType() {
        System.out.println("Execute method asynchronously - "
                + Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
            return new AsyncResult<String>("hello world !!!!");
        } catch (InterruptedException e) {
            //
        }

        return null;
    }
}

异步方法调用:

public class Main{

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        AsyncJob async = ctx.getBean(AsyncJob.class);
        System.out.println("start...");

        async.asyncMethodWithVoidReturnType();

        Future<String> ret = async.asyncMethodWithReturnType();

        try {
            System.out.println(ret.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("end...");
    }

}

上一篇 下一篇

猜你喜欢

热点阅读