异步方法调用是希望快速相应前台界面,而不至于应为后台操作太慢了卡死在哪里。 例如:
package springboot.service; import org.springframework.stereotype.Service; @Service public class ServiceImpl implements IService{ @Override public void testAsync() { new Thread(()->{ //业务代码 System.out.println("异步业务开始执行"); long startTime = System.currentTimeMillis(); int count = 5; while(count>0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("倒计时"+count); count--; } long endTime = System.currentTimeMillis(); long usedTime = endTime - startTime; System.out.println("异步业务执行完毕,共耗时"+usedTime); }).start(); } } package springboot.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import springboot.service.IService; @RestController public class HelloController { @Autowired private IService iService; @GetMapping("test") public String test(){ iService.testAsync(); return "调用接口返回"; } }接口调用马上就返回了, 但调用的方法还在后台继续执行
异步任务上加上 @Async注解
@Async public void testAsync(){ System.out.println("异步任务开始执行"); long startTime = System.currentTimeMillis(); int count =5; while(count>=0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } int complete = 100-(100*count/5); System.out.println("任务执行倒计时"+count+",完成"+complete+"%"); count--; } long endTime = System.currentTimeMillis(); long usedTime = endTime - startTime; System.out.println("任务执行完毕,共耗时"+usedTime); }使用异步注解@Async 需要在启动类加上@EnableAsync
package springboot; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync //使用异步注解@Async 需要在这里加上@EnableAsync @MapperScan("springboot.dao") //不可或缺作用是扫描dao包下面的所有mapper装配 public class HelloApplication { public static void main(String[] args) { SpringApplication.run(HelloApplication.class,args); } }Controller调用演示
@GetMapping("testAsync") public ResponseDTO testAsync(){ tUserService.testAsync(); return ResponseDTO.success(); }在浏览器请求,马上就返回了,说明异步注解生效 马上,转到后台,看见异步任务仍在执行
