springboot-异步任务

1 创建一个springboot项目

参考地址:springboot-hello world

创建项目过程中添加web模块

2 同步任务

2.1 创建一个service包,并在该包下编写一个AsyncService

src/main/java/com/lv/service/AsyncService.java

package com.lv.service;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(1000);
System.out.println("过去了1秒");
Thread.sleep(1000);
System.out.println("过去了2秒");
Thread.sleep(1000);
System.out.println("过去了3秒");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}

2.2 创建一个controller包,并在该包下编写一个AsyncController

src/main/java/com/lv/controller/AsyncController.java

package com.lv.controller;
import com.lv.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();//停止四秒,转圈~
return "OK";
}
}

2.3 启动项目测试

访问/hello请求

经过了4秒钟,页面才加入成功

hello方法运行完毕,页面才加载进来

3 异步任务

将上面的例子改为异步操作

3.1 给hello方法添加@Async注解

SpringBoot就会自己开一个线程池,进行调用!但是要让这个注解生效,我们还需要在主程序上添加一个注解@EnableAsync ,开启异步注解功能;

src/main/java/com/lv/service/AsyncService.java

package com.lv.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
//告诉spring这是一个异步的方法
@Async
public void hello(){
try {
Thread.sleep(1000);
System.out.println("过去了1秒");
Thread.sleep(1000);
System.out.println("过去了2秒");
Thread.sleep(1000);
System.out.println("过去了3秒");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}

3.2 在主程序上添加@EnableAsync注解

src/main/java/com/lv/Springboot09TestApplication.java

package com.lv;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class Springboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09TestApplication.class, args);
}
}

3.3 重启项目测试

hello方法还没有,页面就加载进来了,实现了异步操作

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示