亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

淺談SpringBoot實(shí)現(xiàn)異步調(diào)用的幾種方式

 更新時(shí)間:2023年11月03日 11:09:56   作者:qinxun2008081  
本文主要介紹了淺談SpringBoot實(shí)現(xiàn)異步調(diào)用的幾種方式,主要包括CompletableFuture異步任務(wù),基于@Async異步任務(wù), TaskExecutor異步任務(wù),感興趣的可以了解一下

一、使用 CompletableFuture 實(shí)現(xiàn)異步任務(wù)

CompletableFuture 是 Java 8 新增的一個(gè)異步編程工具,它可以方便地實(shí)現(xiàn)異步任務(wù)。使用 CompletableFuture 需要滿足以下條件:

  • 異步任務(wù)的返回值類型必須是 CompletableFuture 類型;

  • 在異步任務(wù)中使用 CompletableFuture.supplyAsync() 或 CompletableFuture.runAsync() 方法來(lái)創(chuàng)建異步任務(wù);

  • 在主線程中使用 CompletableFuture.get() 方法獲取異步任務(wù)的返回結(jié)果。

我們創(chuàng)建一個(gè)服務(wù)類,里面包含了異步方法和普通方法。

import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 異步服務(wù)類
 */
@Service
public class AsyncService {


    /**
     * 普通任務(wù)操作1
     */
    public String task1() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任務(wù)執(zhí)行完成1";
    }

    /**
     * 普通任務(wù)操作2
     */
    public String task2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        return "任務(wù)執(zhí)行完成2";
    }

    /**
     * 普通任務(wù)操作3
     */
    public String task3() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任務(wù)執(zhí)行完成3";
    }

    /**
     * 異步操作1
     */
    public CompletableFuture<String> asyncTask1() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "異步任務(wù)執(zhí)行完成1";
        });
    }

    /**
     * 異步操作2
     */
    public CompletableFuture<String> asyncTask2() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "異步任務(wù)執(zhí)行完成2";
        });
    }

    /**
     * 異步操作3
     */
    public CompletableFuture<String> asyncTask3() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "異步任務(wù)執(zhí)行完成3";
        });
    }
}

我們先測(cè)試普通方法的情況,看看最后耗時(shí)

import cn.hutool.core.date.StopWatch;
import com.example.quartzdemo.service.AsyncService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 異步處理測(cè)試
 */
@SpringBootTest
public class AsyncTest {

    @Autowired
    private AsyncService asyncService;

    @Test
    void test1() throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // 異步操作
       /* CompletableFuture<String> completableFuture1 = asyncService.asyncTask1();
        CompletableFuture<String> completableFuture2 = asyncService.asyncTask2();
        CompletableFuture<String> completableFuture3 = asyncService.asyncTask3();

        System.out.println(completableFuture1.get());
        System.out.println(completableFuture2.get());
        System.out.println(completableFuture3.get());*/

        // 同步操作
        System.out.println(asyncService.task1());
        System.out.println(asyncService.task2());
        System.out.println(asyncService.task3());

        stopWatch.stop();
        System.out.println("耗時(shí):" + stopWatch.getTotalTimeMillis());
    }
}

程序執(zhí)行的結(jié)果:

任務(wù)執(zhí)行完成1
任務(wù)執(zhí)行完成2
任務(wù)執(zhí)行完成3
耗時(shí):8008

我們可以發(fā)現(xiàn),普通同步方法是按順序一個(gè)個(gè)操作的,各個(gè)方法不會(huì)同時(shí)處理。下面我們把這些操作換成異步的方法測(cè)試。

import cn.hutool.core.date.StopWatch;
import com.example.quartzdemo.service.AsyncService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 異步處理測(cè)試
 */
@SpringBootTest
public class AsyncTest {

    @Autowired
    private AsyncService asyncService;

    @Test
    void test1() throws InterruptedException, ExecutionException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // 異步操作
        CompletableFuture&lt;String&gt; completableFuture1 = asyncService.asyncTask1();
        CompletableFuture&lt;String&gt; completableFuture2 = asyncService.asyncTask2();
        CompletableFuture&lt;String&gt; completableFuture3 = asyncService.asyncTask3();

        System.out.println(completableFuture1.get());
        System.out.println(completableFuture2.get());
        System.out.println(completableFuture3.get());

        // 同步操作
        /*System.out.println(asyncService.task1());
        System.out.println(asyncService.task2());
        System.out.println(asyncService.task3());*/

        stopWatch.stop();
        System.out.println("耗時(shí):" + stopWatch.getTotalTimeMillis());
    }
}

程序執(zhí)行結(jié)果:

異步任務(wù)執(zhí)行完成1
異步任務(wù)執(zhí)行完成2
異步任務(wù)執(zhí)行完成3
耗時(shí):3008

發(fā)現(xiàn)幾個(gè)方法是異步同時(shí)進(jìn)行的,沒(méi)有先后的順序,大大提高了程序執(zhí)行效率。

二、基于注解 @Async實(shí)現(xiàn)異步任務(wù)

@Async 注解是 Spring 提供的一種輕量級(jí)異步方法實(shí)現(xiàn)方式,它可以標(biāo)記在方法上,用來(lái)告訴 Spring 這個(gè)方法是一個(gè)異步方法,Spring 會(huì)將這個(gè)方法的執(zhí)行放在異步線程中進(jìn)行。使用 @Async 注解需要滿足以下條件:

  • 需要在 Spring Boot 主類上添加 @EnableAsync 注解啟用異步功能;

  • 需要在異步方法上添加 @Async 注解。

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

@SpringBootApplication
// 主類上加上這個(gè)注解,開啟異步功能
@EnableAsync
public class QuartzDemoApplication {

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

}

修改測(cè)試的服務(wù)層

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

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 異步服務(wù)類
 */
@Service
public class AsyncService {


    /**
     * 同步任務(wù)操作1
     */
    public String task1() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任務(wù)執(zhí)行完成1";
    }

    /**
     * 同步任務(wù)操作2
     */
    public String task2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        return "任務(wù)執(zhí)行完成2";
    }

    /**
     * 同步任務(wù)操作3
     */
    public String task3() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任務(wù)執(zhí)行完成3";
    }


    /**
     * 異步操作1
     */
    @Async
    public Future<String> asyncTask1() throws InterruptedException {
        long currentTimeMillis = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(3);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task1任務(wù)耗時(shí):" + (currentTimeMillis1 - currentTimeMillis) + "ms");
        return new AsyncResult<>("task1完成");
    }

    /**
     * 異步操作2
     */
    @Async
    public Future<String> asyncTask2() throws InterruptedException {
        long currentTimeMillis = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(2);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task1任務(wù)耗時(shí):" + (currentTimeMillis1 - currentTimeMillis) + "ms");
        return new AsyncResult<>("task2完成");
    }

    /**
     * 異步操作3
     */
    @Async
    public Future<String> asyncTask3() throws InterruptedException {
        long currentTimeMillis = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(3);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task1任務(wù)耗時(shí):" + (currentTimeMillis1 - currentTimeMillis) + "ms");
        return new AsyncResult<>("task3完成");
    }

}

創(chuàng)建一個(gè)測(cè)試類

import com.example.quartzdemo.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion:
 */
@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;


    /**
     * 測(cè)試異步
     */
    @RequestMapping("/async")
    public String testAsync() throws InterruptedException, ExecutionException {
        long currentTimeMillis = System.currentTimeMillis();

        Future<String> task1 = asyncService.asyncTask1();
        Future<String> task2 = asyncService.asyncTask2();
        Future<String> task3 = asyncService.asyncTask3();
        while (true) {
            if (task1.isDone() && task2.isDone() && task3.isDone()) {
                // 三個(gè)任務(wù)都調(diào)用完成,退出循環(huán)等待
                break;
            }
        }
        System.out.println(task1.get());
        System.out.println(task2.get());
        System.out.println(task3.get());
        long currentTimeMillis1 = System.currentTimeMillis();
        return "task任務(wù)總耗時(shí):" + (currentTimeMillis1 - currentTimeMillis) + "ms";
    }
}

執(zhí)行測(cè)試方法

task1任務(wù)耗時(shí):2006ms
task1任務(wù)耗時(shí):3011ms
task1任務(wù)耗時(shí):3011ms
task1完成
task2完成
task3完成

三、使用 TaskExecutor 實(shí)現(xiàn)異步任務(wù)

TaskExecutor 是 Spring 提供的一個(gè)接口,它定義了一個(gè)方法 execute(),用來(lái)執(zhí)行異步任務(wù)。使用 TaskExecutor 需要滿足以下條件:

  • 需要在 Spring 配置文件中配置一個(gè) TaskExecutor 實(shí)例;

  • 在異步方法中調(diào)用 TaskExecutor 實(shí)例的 execute() 方法來(lái)執(zhí)行異步任務(wù)。

創(chuàng)建一個(gè)異步配置類

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import java.util.concurrent.Executor;
 
/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 異步處理配置類
 */
@Configuration
public class AsyncConfig implements AsyncConfigurer {
 
    @Bean(name = "asyncExecutor")
    public TaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("async-");
        executor.initialize();
        return executor;
    }
 
    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor();
    }
 
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

修改下服務(wù)類,我們使用自定義的異步配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 異步服務(wù)類
 */
@Service
public class AsyncService {

    @Autowired
    @Qualifier("asyncExecutor")
    private TaskExecutor taskExecutor;


    /**
     * 同步任務(wù)操作1
     */
    public String task1() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任務(wù)執(zhí)行完成1";
    }

    /**
     * 同步任務(wù)操作2
     */
    public String task2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        return "任務(wù)執(zhí)行完成2";
    }

    /**
     * 同步任務(wù)操作3
     */
    public String task3() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任務(wù)執(zhí)行完成3";
    }


    /**
     * 異步操作1
     */
    @Async
    public void asyncTask1() {
        taskExecutor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println("異步任務(wù)執(zhí)行完成1");
    }

    /**
     * 異步操作2
     */
    @Async
    public void asyncTask2() throws InterruptedException {
        taskExecutor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println("異步任務(wù)執(zhí)行完成2");
    }

    /**
     * 異步操作3
     */
    @Async
    public void asyncTask3() throws InterruptedException {
        taskExecutor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println("異步任務(wù)執(zhí)行完成3");
    }
    
}

測(cè)試類進(jìn)行測(cè)試

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 異步處理測(cè)試
 */
@SpringBootTest
public class AsyncTest {
    
    @Autowired
    @Qualifier("asyncExecutor")
    private TaskExecutor taskExecutor;


    @Test
    void test1() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // 異步操作
       /* asyncService.asyncTask1();
        asyncService.asyncTask2();
        asyncService.asyncTask3();*/
        taskExecutor.execute(() -> System.out.println("異步任務(wù)"));

        // 同步操作
        /*System.out.println(asyncService.task1());
        System.out.println(asyncService.task2());
        System.out.println(asyncService.task3());*/

        stopWatch.stop();
        System.out.println("耗時(shí):" + stopWatch.getTotalTimeMillis());
    }
}

耗時(shí):6
異步任務(wù)執(zhí)行完成3
異步任務(wù)執(zhí)行完成1
異步任務(wù)執(zhí)行完成2

到此這篇關(guān)于淺談SpringBoot實(shí)現(xiàn)異步調(diào)用的幾種方式的文章就介紹到這了,更多相關(guān)SpringBoot 異步調(diào)用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論