springboot中使用异步任务

在springboot中使用简单的异步任务

同步情况

首先来看一下同步情况下的代码,在service中添加了一个线程等待方法

@Service
public class AsyncService {

    public void asyncHello(){
        try {
            Thread.sleep(3000);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello...");
    }
}

在controller中当收到“/”请求时,会执行service中的asyncHello()方法再返回success;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;


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

执行结果为 页面加载3秒后才显示success,控制台同时输出“hello...”

异步情况

在应用入口类上添加@EnableAsync注解开启异步

@EnableAsync
@SpringBootApplication
public class DemoApplication {

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

在service的方法上加上@Async注解

@Service
public class AsyncService {

    @Async
    public void asyncHello(){
        try {
            Thread.sleep(3000);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello...");
    }
}

经过以上修改后,运行结果变为立即返回success,在等待3秒后,控制台打印“hello...”

猜你喜欢

转载自blog.csdn.net/qq_40995335/article/details/81271721
今日推荐