springboot開啓異步註解功能

主要記錄內容:

在springboot中如何開啓異步註解功能,異步註解功能開啓後,可以讓在調用異步功能時,系統可以自動接着往下走,而不用一直在等待異步功能完成纔可以接着走下一步任務。

前提:內容時基於springboot實現的。

一、service層代碼:在service中定義了一個測試異步的代碼:在方法上增加@Async註解

package com.demo.service;

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

@Service
public class AsyncService {

    // @Async 告訴spring 這個一個異步方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("數據處理中.....");

    }
}

二、springboot默認是不開啓異步註解功能的,所以,要讓springboot中識別@Async,則必須在入口文件中,開啓異步註解功能

package com.demo;

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

//開啓異步註解功能
@EnableAsync
@SpringBootApplication
public class SpringbootTaskApplication {

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

}

三、這樣,當在controller層中調用service層的異步方法時,方法會異步進行,前端不會一直處於等待中

package com.demo.controller;

import com.demo.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
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello() {
        this.asyncService.hello();//停止三秒
        return "success";
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章