SpringCloud(第 047 篇)註解式Async配置異步任務

SpringCloud(第 047 篇)註解式Async配置異步任務

-

一、大致介紹

1、有時候我們在處理一些任務的時候,需要開啓線程去異步去處理,原有邏輯繼續往下執行;
2、當遇到這種場景的時候,線程是可以將我們完成,然後在SpringCloud中也有這樣的註解來支撐異步任務處理;

二、實現步驟

2.1 添加 maven 引用包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springms-async</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.springms.cloud</groupId>
        <artifactId>springms-spring-cloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <dependencies>
        <!-- web模塊 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>

2.2 添加應用配置文件(springms-async\src\main\resources\application.yml)

server:
  port: 8345
spring:
  application:
    name: springms-async  #全部小寫

2.3 添加異步任務類(springms-async\src\main\java\com\springms\cloud\task\AsyncTasks.java)

package com.springms.cloud.task;

import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.concurrent.Future;

/**
 * Async實現異步調用。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/10/19
 *
 */
@Component
public class AsyncTasks {

    public static Random random = new Random();

    @Async
    public Future<String> doTaskOne() throws Exception {
        System.out.println("Async, taskOne, Start...");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("Async, taskOne, End, 耗時: " + (end - start) + "毫秒");
        return new AsyncResult<>("AsyncTaskOne Finished");
    }

    @Async
    public Future<String> doTaskTwo() throws Exception {
        System.out.println("Async, taskTwo, Start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        System.out.println("Async, taskTwo, End, 耗時: " + (end - start) + "毫秒");
        return new AsyncResult<>("AsyncTaskTwo Finished");
    }

    @Async
    public Future<String> doTaskThree() throws Exception {
        System.out.println("Async, taskThree, Start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        System.out.println("Async, taskThree, End, 耗時: " + (end - start) + "毫秒");
        return new AsyncResult<>("AsyncTaskThree Finished");
    }
}

2.4 添加異步任務Web控制器(springms-async\src\main\java\com\springms\cloud\controller\AsyncTaskController.java)

package com.springms.cloud.controller;

import com.springms.cloud.task.AsyncTasks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

/**
 * 測試異步任務Web控制器。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/10/19
 *
 */
@RestController
public class AsyncTaskController {

    @Autowired
    AsyncTasks asyncTasks;

    /**
     * 測試異步任務。
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/task")
    public String task() throws Exception {
        long start = System.currentTimeMillis();

        Future<String> task1 = asyncTasks.doTaskOne();
        Future<String> task2 = asyncTasks.doTaskTwo();
        Future<String> task3 = asyncTasks.doTaskThree();

        while(true) {
            if(task1.isDone() && task2.isDone() && task3.isDone()) {
                // 三個任務都調用完成,退出循環等待
                break;
            }
            Thread.sleep(1000);
        }

        long end = System.currentTimeMillis();

        String result = "任務全部完成,總耗時:" + (end - start) + "毫秒";
        return result;
    }
}

2.5 添加微服務啓動類(springms-schedule\src\main\java\com\springms\cloud\MsScheduleApplication.java)

package com.springms.cloud;

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

/**
 * 註解式Async配置異步任務;
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/10/19
 *
 */
@SpringBootApplication
@EnableAsync
public class MsAsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(MsAsyncApplication.class, args);
        System.out.println("【【【【【【 Async異步任務微服務 】】】】】】已啓動.");
    }
}

三、測試

/****************************************************************************************
 一、簡單用戶鏈接Mysql數據庫微服務(Async實現異步調用):

 1、添加註解 EnableAsync、Async 以及任務類上註解 Component ;
 2、啓動 springms-async 模塊服務,啓動1個端口;
 3、然後在瀏覽器輸入地址 http://localhost:8345/task 然後等待大約10多秒後,成功打印所有信息,一切正常;

 總結:說明 Async 異步任務配置生效了;
 ****************************************************************************************/

四、下載地址

https://gitee.com/ylimhhmily/SpringCloudTutorial.git

SpringCloudTutorial交流QQ羣: 235322432

SpringCloudTutorial交流微信羣: 微信溝通羣二維碼圖片鏈接

歡迎關注,您的肯定是對我最大的支持!!!

-
<上一篇        首頁        下一篇>

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