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方法還沒有,頁面就加載進來了,實現了異步操作


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM