springboot-异步任务
简单测试使用
异步任务可以简单理解为 前端先立刻返回OK之类的已经做完的信息 然后后端还在运行任务
编写service类 并通过注解告诉springboot为异步任务
package com.jie.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsynService {
//告诉springboot这是一个异步方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理");
}
}
package com.jie.controller;
import com.jie.service.AsynService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsynController {
@Autowired
AsynService asynService;
@RequestMapping("/hello")
public String hello(){
asynService.hello();
return "ok";
}
}
package com.jie;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
//开启异步功能
@EnableAsync
@SpringBootApplication
public class SpringbootAsynApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAsynApplication.class, args);
}
}