springboot-异步任务

1 创建一个springboot项目

参考地址:springboot-hello world

创建项目过程中添加web模块

2 同步任务

2.1 创建一个service包,并在该包下编写一个AsyncService

src/main/java/com/lv/service/AsyncService.java

package com.lv.service;

import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    public void hello(){
        try {
            Thread.sleep(1000);
            System.out.println("过去了1秒");
            Thread.sleep(1000);
            System.out.println("过去了2秒");
            Thread.sleep(1000);
            System.out.println("过去了3秒");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理...");
    }
}

2.2 创建一个controller包,并在该包下编写一个AsyncController

src/main/java/com/lv/controller/AsyncController.java

package com.lv.controller;

import com.lv.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();//停止四秒,转圈~
        return "OK";
    }
}

2.3 启动项目测试

访问/hello请求

经过了4秒钟,页面才加入成功

hello方法运行完毕,页面才加载进来

3 异步任务

将上面的例子改为异步操作

3.1 给hello方法添加@Async注解

SpringBoot就会自己开一个线程池,进行调用!但是要让这个注解生效,我们还需要在主程序上添加一个注解@EnableAsync ,开启异步注解功能;

src/main/java/com/lv/service/AsyncService.java

package com.lv.service;

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

@Service
public class AsyncService {
    //告诉spring这是一个异步的方法
    @Async
    public void hello(){
        try {
            Thread.sleep(1000);
            System.out.println("过去了1秒");
            Thread.sleep(1000);
            System.out.println("过去了2秒");
            Thread.sleep(1000);
            System.out.println("过去了3秒");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理...");
    }
}

3.2 在主程序上添加@EnableAsync注解

src/main/java/com/lv/Springboot09TestApplication.java

package com.lv;

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

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

3.3 重启项目测试

hello方法还没有,页面就加载进来了,实现了异步操作

posted @ 2022-03-10 13:42  从0开始丿  阅读(1202)  评论(0编辑  收藏  举报