240_异步任务


创建项目

image.png
image.png

开启异步注解功能 @EnableAsync

package com.qing;

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

@EnableAsync // 开启异步注解功能
@SpringBootApplication
public class Springboot10TaskApplication {

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

}

标注方法为异步方法 @Async

package com.qing.service;

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

@Service
public class AsyncService {

    @Async // 标注方法为异步方法,告诉Spring这是一个异步方法,需要多线程处理
    public void hello() {
        System.out.println("数据开始处理。。。");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据处理结束");
    }
}

Controller调用

package com.qing.controller;

import com.qing.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/hello")
    public String hello() {
        asyncService.hello();
        return "OK";
    }
}

测试

页面没有卡3秒后,才返回OK
image.png
image.png

posted @ 2022-02-09 17:09  清风(学习-踏实)  阅读(39)  评论(0)    收藏  举报