最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java?SpringBoot?@Async實(shí)現(xiàn)異步任務(wù)的流程分析

 更新時(shí)間:2022年12月27日 11:06:48   作者:彭世瑜  
這篇文章主要介紹了Java?SpringBoot?@Async實(shí)現(xiàn)異步任務(wù),主要包括@Async?異步任務(wù)-無(wú)返回值,@Async?異步任務(wù)-有返回值,@Async?+?自定義線程池的操作代碼,需要的朋友可以參考下

依賴pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.7</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	
	<properties>
		<java.version>1.8</java.version>
	</properties>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

1、同步任務(wù)

應(yīng)用啟動(dòng)類

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

}

同步任務(wù),耗時(shí)2秒

package com.example.demo.service;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
@Slf4j
public class TaskService {
    /**
     * 同步任務(wù)
     * @throws InterruptedException
     */
    public void syncTask() throws InterruptedException {
        Thread.sleep(1000 * 2);
        System.out.println("syncTask");
    }
}

控制器

package com.example.demo.controller;

import com.example.demo.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {
    @Autowired
    private TaskService taskService;

    @GetMapping("/syncTask")
    public String syncTask() throws InterruptedException {
        long start = System.currentTimeMillis();

        taskService.syncTask();

        long end = System.currentTimeMillis();
        log.info("time: {}", end - start);

        return "success";
    }
}

請(qǐng)求接口:等待2秒后返回

GET http://localhost:8080/task/syncTask
Accept: application/json·

2、@Async 異步任務(wù)-無(wú)返回值

啟動(dòng)類需要加上注解:@EnableAsync

package com.example.demo;

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

@SpringBootApplication
@EnableAsync
public class Application {

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

}

異步任務(wù)

package com.example.demo.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
@Slf4j
public class TaskService {
    /**
     * 異步任務(wù)
     * @throws InterruptedException
     */
    @Async
    public void asyncTask() throws InterruptedException {
        Thread.sleep(1000 * 2);
        System.out.println("asyncTask");
    }
}

控制器

package com.example.demo.controller;

import com.example.demo.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {
    @Autowired
    private TaskService taskService;

    @GetMapping("/asyncTask")
    public String asyncTask() throws InterruptedException {
        long start = System.currentTimeMillis();

        taskService.asyncTask();

        long end = System.currentTimeMillis();
        log.info("time: {}", end - start);

        return "success";

    }
}

請(qǐng)求接口:無(wú)等待,直接返回

GET http://localhost:8080/task/asyncTask
Accept: application/json

3、@Async 異步任務(wù)-有返回值

異步任務(wù)

package com.example.demo.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
@Slf4j
public class TaskService {
   /**
    * 異步任務(wù), 有返回值
    * @throws InterruptedException
    */
   @Async
   public Future<String> asyncTaskFuture() throws InterruptedException {
       Thread.sleep(1000 * 2);
       System.out.println("asyncTaskFuture");

       return new AsyncResult<>("asyncTaskFuture");
   }
}

控制器

package com.example.demo.controller;

import com.example.demo.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {
    @Autowired
    private TaskService taskService;

    @GetMapping("/asyncTaskFuture")
    public String asyncTaskFuture() throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();

        Future<String> future = taskService.asyncTaskFuture();

        // 線程等待結(jié)果返回
        String result = future.get();

        long end = System.currentTimeMillis();
        log.info("time: {}", end - start);

        return result;
    }
}

請(qǐng)求接口:等待2秒后返回

GET http://localhost:8080/task/asyncTaskFuture
Accept: application/json

4、@Async + 自定義線程池

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定義線程池
 */
@Configuration
public class ExecutorAsyncConfig {

    @Bean(name = "newAsyncExecutor")
    public Executor newAsync() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();

        // 設(shè)置核心線程數(shù)
        taskExecutor.setCorePoolSize(10);
        // 線程池維護(hù)線程的最大數(shù)量,只有在緩沖隊(duì)列滿了以后才會(huì)申請(qǐng)超過核心線程數(shù)的線程
        taskExecutor.setMaxPoolSize(100);
        // 緩存隊(duì)列
        taskExecutor.setQueueCapacity(50);
        // 允許的空閑時(shí)間,當(dāng)超過了核心線程數(shù)之外的線程在空閑時(shí)間到達(dá)之后會(huì)被銷毀
        taskExecutor.setKeepAliveSeconds(200);
        // 異步方法內(nèi)部線程名稱
        taskExecutor.setThreadNamePrefix("my-xiaoxiao-AsyncExecutor-");
        // 拒絕策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();

        return taskExecutor;
    }
}

異步任務(wù)

package com.example.demo.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
@Slf4j
public class TaskService {
   /**
    * 自定義線程池 執(zhí)行異步任務(wù)
    * @throws InterruptedException
    */
   @Async("newAsyncExecutor")
   public void asyncTaskNewAsync() throws InterruptedException {
       Thread.sleep(1000 * 2);

       System.out.println("asyncTaskNewAsync");

   }
}

控制器

package com.example.demo.controller;

import com.example.demo.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {
    @Autowired
    private TaskService taskService;

    @GetMapping("/asyncTaskNewAsync")
    public String asyncTaskNewAsync() throws InterruptedException {
        long start = System.currentTimeMillis();

        taskService.asyncTaskNewAsync();

        long end = System.currentTimeMillis();
        log.info("time: {}", end - start);

        return "success";
    }
}

請(qǐng)求接口:無(wú)等待,直接返回

GET http://localhost:8080/task/asyncTaskNewAsync
Accept: application/json

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

不需要在啟動(dòng)類上加@EnableAsync 注解,也不需要在方法上加@Async 注解

控制器

package com.example.demo.controller;

import com.example.demo.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {

    @GetMapping("/completableFuture")
    public String completableFuture(){
        long start = System.currentTimeMillis();

        // CompletableFuture實(shí)現(xiàn)異步任務(wù)
        CompletableFuture<Void> result = CompletableFuture.runAsync(() -> {

            try {
                Thread.sleep(1000 * 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("CompletableFuture");
        });

        long end = System.currentTimeMillis();
        log.info("time: {}", end - start);

        return "success";
    }

}

參考
SpringBoot使用@Async的總結(jié)!

到此這篇關(guān)于Java SpringBoot @Async實(shí)現(xiàn)異步任務(wù)的文章就介紹到這了,更多相關(guān)SpringBoot @Async異步任務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java分布式session存儲(chǔ)解決方案圖解

    Java分布式session存儲(chǔ)解決方案圖解

    這篇文章主要介紹了Java分布式session存儲(chǔ)解決方案圖解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • SpringBoot+Querydsl?框架實(shí)現(xiàn)復(fù)雜查詢解析

    SpringBoot+Querydsl?框架實(shí)現(xiàn)復(fù)雜查詢解析

    本篇主要將介紹的是利用spring query dsl框架實(shí)現(xiàn)的服務(wù)端查詢解析和實(shí)現(xiàn)介紹,對(duì)SpringBoot?Querydsl?查詢操作感興趣的朋友一起看看吧
    2022-05-05
  • restTemplate實(shí)現(xiàn)跨服務(wù)API調(diào)用方式

    restTemplate實(shí)現(xiàn)跨服務(wù)API調(diào)用方式

    這篇文章主要介紹了restTemplate實(shí)現(xiàn)跨服務(wù)API調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。
    2023-07-07
  • Yml轉(zhuǎn)properties文件工具類YmlUtils的詳細(xì)過程(不用引任何插件和依賴)

    Yml轉(zhuǎn)properties文件工具類YmlUtils的詳細(xì)過程(不用引任何插件和依賴)

    這篇文章主要介紹了Yml轉(zhuǎn)properties文件工具類YmlUtils(不用引任何插件和依賴),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • java中線程池的關(guān)閉問題

    java中線程池的關(guān)閉問題

    這篇文章主要介紹了java中線程池的關(guān)閉問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 老生常談Java String字符串(必看篇)

    老生常談Java String字符串(必看篇)

    下面小編就為大家?guī)?lái)一篇老生常談Java String字符串(必看篇)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧
    2017-08-08
  • Java中easypoi的使用之導(dǎo)入校驗(yàn)

    Java中easypoi的使用之導(dǎo)入校驗(yàn)

    因工作需要,使用easypoi導(dǎo)入表格,并進(jìn)行校驗(yàn),將表格中有問題的地方,給出提示信息,以表格形式返回,下面這篇文章主要給大家介紹了關(guān)于Java中easypoi的使用之導(dǎo)入校驗(yàn)的相關(guān)資料,需要的朋友可以參考下
    2023-03-03
  • Java將json字符串轉(zhuǎn)換為數(shù)組的幾種方法

    Java將json字符串轉(zhuǎn)換為數(shù)組的幾種方法

    在Java開發(fā)中,經(jīng)常會(huì)遇到將json字符串轉(zhuǎn)換為數(shù)組的需求,本文主要介紹了Java將json字符串轉(zhuǎn)換為數(shù)組的幾種方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-01-01
  • Spring動(dòng)態(tài)添加定時(shí)任務(wù)的實(shí)現(xiàn)思路

    Spring動(dòng)態(tài)添加定時(shí)任務(wù)的實(shí)現(xiàn)思路

    這篇文章主要介紹了Spring動(dòng)態(tài)添加定時(shí)任務(wù)的實(shí)現(xiàn)思路,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-07-07
  • MyBatis Plus構(gòu)建一個(gè)簡(jiǎn)單的項(xiàng)目的實(shí)現(xiàn)

    MyBatis Plus構(gòu)建一個(gè)簡(jiǎn)單的項(xiàng)目的實(shí)現(xiàn)

    這篇文章主要介紹了MyBatis Plus構(gòu)建一個(gè)簡(jiǎn)單的項(xiàng)目的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11

最新評(píng)論

锦屏县| 西藏| 溆浦县| 大冶市| 萍乡市| 陈巴尔虎旗| 霍林郭勒市| 铜梁县| 通州市| 太保市| 哈尔滨市| 禄劝| 和龙市| 临高县| 宽甸| 三门县| 连州市| 阳东县| 益阳市| 瓦房店市| 纳雍县| 剑阁县| 天等县| 枣阳市| 梁河县| 蓝山县| 淳化县| 宣汉县| 绥芬河市| 贵阳市| 连云港市| 嫩江县| 达州市| 西藏| 齐齐哈尔市| 胶南市| 汾西县| 武胜县| 丹棱县| 竹山县| 汝南县|