侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 747 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

SpringBoot(33)之编写一个异步服务

zze
zze
2018-08-23 / 0 评论 / 0 点赞 / 572 阅读 / 1810 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

1、使用 Maven 创建 SpringBoot 项目,引入 Web 场景启动器。

2、编写异步服务类,注册到 IoC 容器:

// zze.springboot.task.service.AsyncService
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    @Async // 标识方法将会异步执行
    public void hello() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello");
    }
}

3、使用注解开启异步任务支持:

// zze.springboot.task.TaskApplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync // 开启异步任务支持
@SpringBootApplication
public class TaskApplication {

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

}

4、编写控制器测试:

// zze.springboot.task.controller.AsyncController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import zze.springboot.task.service.AsyncService;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/hello")
    public String testAsyncHello(){
        asyncService.hello();
        return "执行完毕";
        /*
        访问 localhost:8080/hello
            a、立即返回了 “执行完毕”,并没有因为 asyncService.hello() 方法中的线程 sleep 等待 3 秒。
            b、3 秒后控制台输出 hello
        OK,异步任务执行成功
         */
    }
}
0

评论区