这篇文章将为大家详细讲解有关SpringBoot任务之异步任务的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。一、springBoot--异步任务 1.1 什么是同步和异步同步是阻塞模式
这篇文章将为大家详细讲解有关SpringBoot任务之异步任务的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
同步是阻塞模式,异步是非阻塞模式。
同步就是指一个进程在执行某个请求的时候,若该请求需要一段时间才能返回信息,那么这个进程将会—直等待下去,知道收到返回信息才继续执行下去
异步是指进程不需要一直等下去,而是继续执行下面的操作,不管其他进程的状态。当有消息返回式系统会通知进程进行处理,这样可以提高执行的效率。
AsyncService.java
package com.tian.asyncdemo.service;import org.springframework.stereotype.Service;@Servicepublic class AsyncService { public void hello() { try { System.out.println("数据正在处理"); Thread.sleep(3000); System.out.println("数据处理完成"); } catch (InterruptedException e) { e.printStackTrace(); } }}
AsyncController.java
package com.tian.asyncdemo.controller;import com.tian.asyncdemo.service.AsyncService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.WEB.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class AsyncController { @Autowired AsyncService asyncService; @RequestMapping("/hello") public String hello() { asyncService.hello(); return "OK"; }}
运行结果:
在Service的方法中使用@Async说这是一个异步方法,并在主入口上使用@EnableAsync开启异步支持
AsyncService.java
@Servicepublic class AsyncService { @Async public void hello() { try { System.out.println("数据正在处理"); Thread.sleep(3000); System.out.println("数据处理完成"); } catch (InterruptedException e) { e.printStackTrace(); } }}
主入口上使用@EnableAsync开启异步支持
再次测试:
关于“Springboot任务之异步任务的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
--结束END--
本文标题: Springboot任务之异步任务的示例分析
本文链接: https://www.lsjlt.com/news/279449.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-02
2024-05-02
2024-05-02
2024-05-02
2024-05-02
2024-05-02
2024-05-02
2024-05-02
2024-05-02
2024-05-02
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0