springboot 异步任务

在主类开始任务

package com.sugon.dataexchangeplatform;

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


@EnableAsync //开启异步注解功能
@SpringBootApplication
public class DataExChangePlatformApplication {
    public static void main(String[] args) {
        SpringApplication.run(DataExChangePlatformApplication.class, args);
    }

}

使用异步

@Service
public class AsyncService {
    @Async  //告诉Spring这是一个异步的方法
    public void hello(){
        try {
            Thread.sleep(5000);//休眠5s
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理...");
    }
}

调用

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;
 
    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();   //执行业务层hello方法:停止5s
        return "hello";
    }
}
posted @ 2024-07-31 14:28  vx_guanchaoguo0  阅读(9)  评论(0编辑  收藏  举报