service.TasksService
package com.lu.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class TasksService {
@Async//告诉springboot这是个异步任务
public void Hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理中");
}
}
controller.textController
package com.lu.controller;
import com.lu.service.TasksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TextController {
@Autowired
TasksService tasksService;
@RequestMapping("/hello")
public String hello(){
tasksService.Hello();
return "你好啊";
}
}
运行主类
package com.lu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync//开启异步功能
@SpringBootApplication
public class SpringbootTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTasksApplication.class, args);
}
}