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

springboot 异步任务

时间:2024-07-31 14:28:48浏览次数:17  
标签:异步 springboot springframework class public 任务 import hello

在主类开始任务

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";
    }
}

标签:异步,springboot,springframework,class,public,任务,import,hello
From: https://www.cnblogs.com/guanchaoguo/p/17116947.html

相关文章