您好,欢迎访问一九零五行业门户网

SpringBoot怎么优雅地实现异步调用

前言同步编程:在同步编程中,任务一次执行一个,只有当一个任务完成时,下一个任务才会被解除阻塞。
异步编程:在异步编程中,可以同时执行多个任务。您可以在上一个任务完成之前转到另一个任务。
在spring boot中,我们可以使用@async注解来实现异步行为。
实现步骤1.定义一个异步服务接口asyncservice.java
public interface asyncservice { void asyncmethod() throws interruptedexception; future<string> futuremethod() throws interruptedexception;}
2.实现定义的接口asyncserviceimpl.java
@service@slf4jpublic class asyncserviceimpl implements asyncservice { @async @override public void asyncmethod() throws interruptedexception { thread.sleep(3000); log.info("thread: [{}], calling other service..", thread.currentthread().getname()); } @async @override public future<string> futuremethod() throws interruptedexception { thread.sleep(5000); log.info("thread: [{}], calling other service..", thread.currentthread().getname()); return new asyncresult<>("task done"); }}
asyncserviceimpl 是一个 spring 管理的 bean。
您的异步方法必须是公共的,而且是被@async注解修饰。
返回类型被限制为 void 或 future。
3.定义一个控制器asynccontroller.java
@enableasync@restcontroller@slf4jpublic class asynccontroller { @autowired asyncservice asyncservice; @getmapping("/async") public string asynccallermethod() throws interruptedexception { long start = system.currenttimemillis(); log.info("call async method, thread name: [{}]", thread.currentthread().getname()); asyncservice.asyncmethod(); string response = "task completes in :" + (system.currenttimemillis() - start) + "milliseconds"; return response; } @getmapping("/asyncfuture") public string asyncfuture() throws interruptedexception, executionexception { long start = system.currenttimemillis(); log.info("call async method, thread name: [{}]", thread.currentthread().getname()); future<string> future = asyncservice.futuremethod(); // 阻塞获取结果 string taskresult = future.get(); string response = taskresult + "task completes in :" + (system.currenttimemillis() - start) + "milliseconds"; return response; }}
关键点,需要添加启用异步的注解@enableasync ,当然这个注解加在其他地方也ok得。
当外部调用该接口时,asyncmethod()将由默认任务执行程序创建的另一个线程执行,主线程不需要等待完成异步方法执行。
4.运行一下
现在我们运行一下看看,是不是异步返回的。
可以看到调用/async接口,最终一步调用了方法。
调用/asyncfuture,发现返回5秒多,难道不是异步的吗?其实也是异步的,看日志可以看出来,只不过我们返回的是future,调用futrue.get()是阻塞的。
自定义异步任务执行器和异常处理我们现在看看如果异常方法中报错了会怎么样?修改异步代码如下所示,会抛运行时异常:
再次执行异步接口,如下所示,会使用默认的线程池和异常处理。
我们也可以自定义异步方法的处理异常和异步任务执行器,我们需要配置 asyncuncaughtexceptionhandler,如下代码所示:
@configurationpublic class asynconfiguration extends asyncconfigurersupport { @override public executor getasyncexecutor() { threadpooltaskexecutor executor = new threadpooltaskexecutor(); executor.setcorepoolsize(3); executor.setmaxpoolsize(4); executor.setthreadnameprefix("asyn-task-thread-"); executor.setwaitfortaskstocompleteonshutdown(true); executor.initialize(); return executor; } @override public asyncuncaughtexceptionhandler getasyncuncaughtexceptionhandler() { return new asyncuncaughtexceptionhandler() { @override public void handleuncaughtexception(throwable ex, method method, object... params) { system.out.println("exception: " + ex.getmessage()); system.out.println("method name: " + method.getname()); ex.printstacktrace(); } }; }}
再次运行,得到的结果如下:
@async如何工作的必须通过使用 @enableasync注解注解主应用程序类或任何直接或间接异步方法调用程序类来启用异步支持。主要通过代理模式实现,默认模式是 proxy,另一种是 aspectj。代理模式只允许通过代理拦截调用。永远不要从定义它的同一个类调用异步方法,它不会起作用。
当使用 @async对方法进行注解时,它会根据“proxytargetclass”属性为该对象创建一个代理。当 spring 执行这个方法时,默认情况下它会搜索关联的线程池定义。上下文中唯一的 spring 框架 taskexecutor bean 或名为“taskexecutor”的 executor bean。如果这两者都不可解析,默认会使用spring框架simpleasynctaskexecutor来处理异步方法的执行。
以上就是springboot怎么优雅地实现异步调用的详细内容。
其它类似信息

推荐信息