您好,登录后才能下订单哦!
这篇文章主要介绍了Spring异步接口返回结果的方式有哪些的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Spring异步接口返回结果的方式有哪些文章都会有所收获,下面我们一起来看看吧。
开发中我们经常遇到异步接口需要执行一些耗时的操作,并且接口要有返回结果。
使用场景:用户绑定邮箱、手机号,将邮箱、手机号保存入库后发送邮件或短信通知
接口要求:数据入库后给前台返回成功通知,后台异步执行发邮件、短信通知操作
一般的话在企业中会借用消息队列来实现发送,业务量大的话有一个统一消费、管理的地方。但有时项目中没有引用mq相关组件,这时为了实现一个功能去引用、维护一个消息组件有点大材小用,下面介绍几种不引用消息队列情况下的解决方式
定义线程池:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; /** * @description: 公共配置 * @author: yh * @date: 2022/8/26 */ @EnableAsync @Configuration public class CommonConfig { @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置核心线程数 executor.setCorePoolSize(50); // 设置最大线程数 executor.setMaxPoolSize(200); // 设置队列容量 executor.setQueueCapacity(200); // 设置线程活跃时间(秒) executor.setKeepAliveSeconds(800); // 设置默认线程名称 executor.setThreadNamePrefix("task-"); // 设置拒绝策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); return executor; } }
定义异步任务,如发送邮件、短信等
@Service public class ExampleServiceImpl implements ExampleService { @Async("taskExecutor") @Override public void sendMail(String email) { try { Thread.sleep(3000); System.out.println("异步任务执行完成, " + email + " 当前线程:" + Thread.currentThread().getName()); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
Controller
@RequestMapping(value = "/api") @RestController public class ExampleController { @Resource private ExampleService exampleService; @RequestMapping(value = "/bind",method = RequestMethod.GET) public String bind(@RequestParam("email") String email) { long startTime = System.currentTimeMillis(); try { // 绑定邮箱....业务 Thread.sleep(2000); } catch (InterruptedException e) { throw new RuntimeException(e); } //模拟异步任务(发邮件通知、短信等) exampleService.sendMail(email); long endTime = System.currentTimeMillis(); System.out.println("方法执行完成返回,耗时:" + (endTime - startTime)); return "ok"; } }
运行结果:
@RequestMapping(value = "/api") @RestController public class ExampleController { @Resource private ExampleService exampleService; @Resource private TaskExecutor taskExecutor; @RequestMapping(value = "/bind", method = RequestMethod.GET) public String bind(@RequestParam("email") String email) { long startTime = System.currentTimeMillis(); try { // 绑定邮箱....业务 Thread.sleep(2000); // 将发送邮件交给线程池去执行 taskExecutor.execute(() -> { exampleService.sendMail(email); }); } catch (InterruptedException e) { throw new RuntimeException(e); } long endTime = System.currentTimeMillis(); System.out.println("方法执行完成返回,耗时:" + (endTime - startTime)); return "ok"; } }
运行结果:
首先去掉Service
方法中的@Async("taskExecutor")
,此时执行就会变成同步,总计需要5s
才能完成接口返回。这次我们使用jdk1.8中的CompletableFuture
来实现异步任务
@RequestMapping(value = "/api") @RestController public class ExampleController { @Resource private ExampleService exampleService; @Resource private TaskExecutor taskExecutor; @RequestMapping(value = "/bind", method = RequestMethod.GET) public String bind(@RequestParam("email") String email) { long startTime = System.currentTimeMillis(); try { // 绑定邮箱....业务 Thread.sleep(2000); // 将发送邮件交给异步任务Future,需要记录返回值用supplyAsync CompletableFuture.runAsync(() -> { exampleService.sendMail(email); }, taskExecutor); } catch (InterruptedException e) { throw new RuntimeException(e); } long endTime = System.currentTimeMillis(); System.out.println("方法执行完成返回,耗时:" + (endTime - startTime)); return "ok"; } }
运行结果:
Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式;为的就是业务系统逻辑的解耦,提高可扩展性以及可维护性。事件发布者并不需要考虑谁去监听,监听具体的实现内容是什么,发布者的工作只是为了发布事件而已。
2.4.1 定义event事件模型
public class NoticeEvent extends ApplicationEvent { private String email; private String phone; public NoticeEvent(Object source, String email, String phone) { super(source); this.email = email; this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
2.4.2 事件监听
@Component public class ComplaintEventListener { /** * 只监听NoticeEvent事件 * @author: yh * @date: 2022/8/27 */ @Async @EventListener(value = NoticeEvent.class) // @Order(1) 指定事件执行顺序 public void sendEmail(NoticeEvent noticeEvent) { //发邮件 try { Thread.sleep(3000); System.out.println("发送邮件任务执行完成, " + noticeEvent.getEmail() + " 当前线程:" + Thread.currentThread().getName()); } catch (InterruptedException e) { throw new RuntimeException(e); } } @Async @EventListener(value = NoticeEvent.class) // @Order(2) 指定事件执行顺序 public void sendMsg(NoticeEvent noticeEvent) { //发短信 try { Thread.sleep(3000); System.out.println("发送短信步任务执行完成, " + noticeEvent.getPhone() + " 当前线程:" + Thread.currentThread().getName()); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
2.4.5 事件发布
@RequestMapping(value = "/api") @RestController public class ExampleController { /** * 用于事件推送 * @author: yh * @date: 2022/8/27 */ @Autowired private ApplicationEventPublisher applicationEventPublisher; @RequestMapping(value = "/bind", method = RequestMethod.GET) public String bind(@RequestParam("email") String email) { long startTime = System.currentTimeMillis(); try { // 绑定邮箱....业务 Thread.sleep(2000); // 发布事件,这里偷个懒手机号写死 applicationEventPublisher.publishEvent(new NoticeEvent(this, email, "13211112222")); } catch (InterruptedException e) { throw new RuntimeException(e); } long endTime = System.currentTimeMillis(); System.out.println("方法执行完成返回,耗时:" + (endTime - startTime)); return "ok"; } }
运行结果:
关于“Spring异步接口返回结果的方式有哪些”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Spring异步接口返回结果的方式有哪些”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。