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

Spring?Boot使用線程池處理上萬條數(shù)據(jù)插入功能

 更新時間:2022年08月09日 16:27:39   作者:java界的阿諾斯瓦辛格  
這篇文章主要介紹了Spring?Boot使用線程池處理上萬條數(shù)據(jù)插入功能,使用步驟是先創(chuàng)建一個線程池的配置,讓Spring Boot加載,用來定義如何創(chuàng)建一個ThreadPoolTaskExecutor,本文通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧

# 前言

前兩天做項目的時候,想提高一下插入表的性能優(yōu)化,因為是兩張表,先插舊的表,緊接著插新的表,一萬多條數(shù)據(jù)就有點慢了

后面就想到了線程池ThreadPoolExecutor,而用的是Spring Boot項目,可以用Spring提供的對ThreadPoolExecutor封裝的線程池ThreadPoolTaskExecutor,直接使用注解啟用

# 使用步驟

先創(chuàng)建一個線程池的配置,讓Spring Boot加載,用來定義如何創(chuàng)建一個ThreadPoolTaskExecutor,要使用@Configuration和@EnableAsync這兩個注解,表示這是個配置類,并且是線程池的配置類

@Configuration
@EnableAsync
public class ExecutorConfig {
    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
    @Value("${async.executor.thread.core_pool_size}")    
    private int corePoolSize;   
    
    @Value("${async.executor.thread.max_pool_size}")    
    private int maxPoolSize;   
    
    @Value("${async.executor.thread.queue_capacity}")  
    private int queueCapacity;   
    
    @Value("${async.executor.thread.name.prefix}")  
    private String namePrefix;
    @Bean(name = "asyncServiceExecutor")    
    public Executor asyncServiceExecutor() {   
        logger.info("start asyncServiceExecutor");    
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 
    
        //配置核心線程數(shù)       
        executor.setCorePoolSize(corePoolSize);   
    
        //配置最大線程數(shù)      
        executor.setMaxPoolSize(maxPoolSize);   
    
        //配置隊列大小     
        executor.setQueueCapacity(queueCapacity);    
    
        //配置線程池中的線程的名稱前綴        
        executor.setThreadNamePrefix(namePrefix);
        // rejection-policy:當(dāng)pool已經(jīng)達到max size的時候,如何處理新任務(wù)        
        // CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是有調(diào)用者所在的線程來執(zhí)行  
         
         executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());     
        //執(zhí)行初始化      
        executor.initialize();   
        return executor;  
     }
}

@Value是我配置在application.properties,可以參考配置,自由定義

# 異步線程配置
# 配置核心線程數(shù)
async.executor.thread.core_pool_size = 5
# 配置最大線程數(shù)
async.executor.thread.max_pool_size = 5
# 配置隊列大小
async.executor.thread.queue_capacity = 99999
# 配置線程池中的線程的名稱前綴
async.executor.thread.name.prefix = async-service-

創(chuàng)建一個Service接口,是異步線程的接口

public interface AsyncService {   
    /**     
      * 執(zhí)行異步任務(wù)     
      * 可以根據(jù)需求,自己加參數(shù)擬定,我這里就做個測試演示    
      */   
    void executeAsync();
}

實現(xiàn)類

@Service
public class AsyncServiceImpl implements AsyncService {  
    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);
    @Override 
    @Async("asyncServiceExecutor")    
    public void executeAsync() {    
        logger.info("start executeAsync");
        System.out.println("異步線程要做的事情");        
        System.out.println("可以在這里執(zhí)行批量插入等耗時的事情");
        logger.info("end executeAsync");   
    }
}

在executeAsync()方法上增加注解@Async("asyncServiceExecutor"),asyncServiceExecutor方法是前面ExecutorConfig.java中的方法名,表明executeAsync方法進入的線程池是asyncServiceExecutor方法創(chuàng)建的

接下來就是在Controller里或者是哪里通過注解@Autowired注入這個Service

@Autowiredprivate 
AsyncService asyncService;

@GetMapping("/async")
public void async(){  
    asyncService.executeAsync();
}

日志打印

 2022-07-16 22:15:47.655  INFO 10516 --- [async-service-5] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
 異步線程要做的事情
 可以在這里執(zhí)行批量插入等耗時的事情
 2022-07-16 22:15:47.655  INFO 10516 --- [async-service-5] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
 2022-07-16 22:15:47.770  INFO 10516 --- [async-service-1] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
 異步線程要做的事情
 可以在這里執(zhí)行批量插入等耗時的事情
 2022-07-16 22:15:47.770  INFO 10516 --- [async-service-1] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
 2022-07-16 22:15:47.816  INFO 10516 --- [async-service-2] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
 異步線程要做的事情
 可以在這里執(zhí)行批量插入等耗時的事情
 2022-07-16 22:15:47.816  INFO 10516 --- [async-service-2] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
 2022-07-16 22:15:48.833  INFO 10516 --- [async-service-3] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
 異步線程要做的事情
 可以在這里執(zhí)行批量插入等耗時的事情
 2022-07-16 22:15:48.834  INFO 10516 --- [async-service-3] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
 2022-07-16 22:15:48.986  INFO 10516 --- [async-service-4] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
 異步線程要做的事情
 可以在這里執(zhí)行批量插入等耗時的事情
 2022-07-16 22:15:48.987  INFO 10516 --- [async-service-4] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync

通過以上日志可以發(fā)現(xiàn),[async-service-]是有多個線程的,顯然已經(jīng)在我們配置的線程池中執(zhí)行了,并且每次請求中,controller的起始和結(jié)束日志都是連續(xù)打印的,表明每次請求都快速響應(yīng)了,而耗時的操作都留給線程池中的線程去異步執(zhí)行;

雖然我們已經(jīng)用上了線程池,但是還不清楚線程池當(dāng)時的情況,有多少線程在執(zhí)行,多少在隊列中等待呢?這里我創(chuàng)建了一個ThreadPoolTaskExecutor的子類,在每次提交線程的時候都會將當(dāng)前線程池的運行狀況打印出來

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.concurrent.Callable;import java.util.concurrent.Future;import java.util.concurrent.ThreadPoolExecutor;
/** 
* @Author: 騰騰 
* @Date: 2022/7/16/0016 22:19 
*/
public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
    private static final Logger logger = LoggerFactory.getLogger(VisiableThreadPoolTaskExecutor.class);
    private void showThreadPoolInfo(String prefix) {        
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
        if (null == threadPoolExecutor) {    
            return;  
        }
        logger.info("{}, {},taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]",                
        this.getThreadNamePrefix(),         
        prefix,           
        threadPoolExecutor.getTaskCount(),     
        threadPoolExecutor.getCompletedTaskCount(),  
        threadPoolExecutor.getActiveCount(),    
        threadPoolExecutor.getQueue().size());
     }
    @Override    
    public void execute(Runnable task) {    
        showThreadPoolInfo("1. do execute");       
        super.execute(task);   
    }
    @Override    
    public void execute(Runnable task, long startTimeout) {      
        showThreadPoolInfo("2. do execute");   
        super.execute(task, startTimeout);  
    }
    @Override  
    public Future<?> submit(Runnable task) {   
        showThreadPoolInfo("1. do submit");    
        return super.submit(task);   
    }
    @Override  
    public <T> Future<T> submit(Callable<T> task) {   
        showThreadPoolInfo("2. do submit");      
        return super.submit(task); 
    }
    @Override    
    public ListenableFuture<?> submitListenable(Runnable task) {    
        showThreadPoolInfo("1. do submitListenable");   
        return super.submitListenable(task);   
    }
    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {     
        showThreadPoolInfo("2. do submitListenable");     
        return super.submitListenable(task);  
    }
}

如上所示,showThreadPoolInfo方法中將任務(wù)總數(shù)、已完成數(shù)、活躍線程數(shù),隊列大小都打印出來了,然后Override了父類的execute、submit等方法,在里面調(diào)用showThreadPoolInfo方法,這樣每次有任務(wù)被提交到線程池的時候,都會將當(dāng)前線程池的基本情況打印到日志中;

修改ExecutorConfig.java的asyncServiceExecutor方法,將ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor()改為ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor()

@Bean(name = "asyncServiceExecutor")    
public Executor asyncServiceExecutor() {  
    logger.info("start asyncServiceExecutor");  
    //在這里修改       
    ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();    
    //配置核心線程數(shù)     
    executor.setCorePoolSize(corePoolSize);  
    //配置最大線程數(shù)      
    executor.setMaxPoolSize(maxPoolSize);  
    //配置隊列大小      
    executor.setQueueCapacity(queueCapacity); 
    //配置線程池中的線程的名稱前綴      
    executor.setThreadNamePrefix(namePrefix);
    
    // rejection-policy:當(dāng)pool已經(jīng)達到max size的時候,如何處理新任務(wù)      
    // CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是有調(diào)用者所在的線程來執(zhí)行     
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); 
    //執(zhí)行初始化       
    executor.initialize();       
    return executor; 
}

再次啟動該工程測試

2022-07-16 22:23:30.951  INFO 14088 --- [nio-8087-exec-2] u.d.e.e.i.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [0], completedTaskCount [0], activeCount [0], queueSize [0]
2022-07-16 22:23:30.952  INFO 14088 --- [async-service-1] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
異步線程要做的事情
可以在這里執(zhí)行批量插入等耗時的事情
2022-07-16 22:23:30.953  INFO 14088 --- [async-service-1] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
2022-07-16 22:23:31.351  INFO 14088 --- [nio-8087-exec-3] u.d.e.e.i.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [1], completedTaskCount [1], activeCount [0], queueSize [0]
2022-07-16 22:23:31.353  INFO 14088 --- [async-service-2] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
異步線程要做的事情
可以在這里執(zhí)行批量插入等耗時的事情
2022-07-16 22:23:31.353  INFO 14088 --- [async-service-2] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
2022-07-16 22:23:31.927  INFO 14088 --- [nio-8087-exec-5] u.d.e.e.i.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [2], completedTaskCount [2], activeCount [0], queueSize [0]
2022-07-16 22:23:31.929  INFO 14088 --- [async-service-3] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
異步線程要做的事情
可以在這里執(zhí)行批量插入等耗時的事情
2022-07-16 22:23:31.930  INFO 14088 --- [async-service-3] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
2022-07-16 22:23:32.496  INFO 14088 --- [nio-8087-exec-7] u.d.e.e.i.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [3], completedTaskCount [3], activeCount [0], queueSize [0]
2022-07-16 22:23:32.498  INFO 14088 --- [async-service-4] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
異步線程要做的事情
可以在這里執(zhí)行批量插入等耗時的事情
2022-07-16 22:23:32.499  INFO 14088 --- [async-service-4] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync

注意這一行日志:

2022-07-16 22:23:32.496  INFO 14088 --- [nio-8087-exec-7] u.d.e.e.i.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [3], completedTaskCount [3], activeCount [0], queueSize [0]

這說明提交任務(wù)到線程池的時候,調(diào)用的是submit(Callable task)這個方法,當(dāng)前已經(jīng)提交了3個任務(wù),完成了3個,當(dāng)前有0個線程在處理任務(wù),還剩0個任務(wù)在隊列中等待,線程池的基本情況一路了然;

到此這篇關(guān)于Spring Boot使用線程池處理上萬條數(shù)據(jù)插入的文章就介紹到這了,更多相關(guān)Spring Boot線程池處理上萬條數(shù)據(jù)插入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java導(dǎo)入新項目報錯java:JDK?isn‘t?specified?for?module解決辦法

    Java導(dǎo)入新項目報錯java:JDK?isn‘t?specified?for?module解決辦法

    這篇文章主要給大家介紹了關(guān)于Java導(dǎo)入新項目報錯java:JDK?isn‘t?specified?for?module的解決辦法,當(dāng)您在導(dǎo)入Java項目時遇到錯誤時,可以嘗試以下面的方法來處理,需要的朋友可以參考下
    2024-05-05
  • mybatis-spring:@MapperScan注解的使用

    mybatis-spring:@MapperScan注解的使用

    這篇文章主要介紹了mybatis-spring:@MapperScan注解的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • spring 自定義讓@Value被解析到

    spring 自定義讓@Value被解析到

    這篇文章主要介紹了spring 自定義讓@Value被解析到,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 詳解Java打包及上傳到私服務(wù)的方法

    詳解Java打包及上傳到私服務(wù)的方法

    這篇文章主要介紹了Java打包及上傳到私服務(wù)的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2024-01-01
  • Maven2 plugin開發(fā)教程詳解

    Maven2 plugin開發(fā)教程詳解

    這篇文章主要為大家詳細介紹了Maven2 plugin的開發(fā)教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Spring?Data?JPA查詢方式及方法名查詢規(guī)則介紹

    Spring?Data?JPA查詢方式及方法名查詢規(guī)則介紹

    這篇文章主要介紹了Spring?Data?JPA查詢方式及方法名查詢規(guī)則,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • java解析.yml文件方式

    java解析.yml文件方式

    這篇文章主要介紹了java解析.yml文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Spring的Bean生命周期之BeanDefinition詳解

    Spring的Bean生命周期之BeanDefinition詳解

    這篇文章主要介紹了Spring的Bean生命周期之BeanDefinition詳解,在spring bean創(chuàng)建過程 依賴 BeanDefinition 中的信息處理bean的生產(chǎn),BeanDefinition 是 Spring Framework 中定義 Bean 的配置元信息接口,需要的朋友可以參考下
    2023-12-12
  • Java獲取Object中Value的實現(xiàn)方法

    Java獲取Object中Value的實現(xiàn)方法

    本文介紹了在Java中獲取對象屬性值的幾種常見方法,包括使用反射機制、getter方法、接口或抽象類、Map數(shù)據(jù)結(jié)構(gòu)、序列化與反序列化以及JavaBeans規(guī)范,每種方法都有其適用場景和優(yōu)缺點,選擇合適的方法取決于具體需求
    2025-03-03
  • Spring中使用JSR303請求約束判空的實現(xiàn)

    Spring中使用JSR303請求約束判空的實現(xiàn)

    這篇文章主要介紹了Spring中使用JSR303請求約束判空的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12

最新評論

波密县| 姚安县| 福建省| 澄城县| 宝山区| 彩票| 夏津县| 盐池县| 常德市| 兴安县| 莱阳市| 常德市| 汽车| 巴林左旗| 浑源县| 丹江口市| 北辰区| 江阴市| 临安市| 泽州县| 伊宁县| 盐津县| 洞口县| 阳曲县| 丰台区| 德昌县| 石嘴山市| 竹溪县| 孟村| 和龙市| 额济纳旗| 南靖县| 晋城| 沅江市| 互助| 平泉县| 吴江市| 吴忠市| 台北市| 阳西县| 泰顺县|