首页 > 其他分享 >springboot任务之异步任务

springboot任务之异步任务

时间:2022-11-30 19:09:01浏览次数:34  
标签:异步 springboottask springboot springframework AsyncService 任务 import org hello


1-新建工程,只选web模块

2-新增service包,AsyncService类

package com.example.springboottask.service;

import org.springframework.stereotype.Service;

@Service
public class AsyncService {

public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中....");
}
}

3-新建controller包,AsyncController类

package com.example.springboottask.controller;

import com.example.springboottask.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

@Autowired
AsyncService asyncService;

@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}

4-访问http://localhost:8080/hello,响应3秒之后出现页面

5-要使这个任务是异步的,需要

5-1给service添加@Async注解

package com.example.springboottask.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

//告诉spring这是一个异步方法
@Async
public void hello(){
try {

5-2给启动类添加@EnableAsync注解


package com.example.springboottask;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync //开启异步注解功能
@SpringBootApplication
public class SpringbootTaskApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}

}

6-运行

此时立即响应,无需等待三秒

标签:异步,springboottask,springboot,springframework,AsyncService,任务,import,org,hello
From: https://blog.51cto.com/u_12528551/5900175

相关文章