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

spring?boot使用@Async注解解決異步多線程入庫的問題

 更新時間:2022年05月27日 10:06:51   作者:jiuchengi  
最近在寫項目是需要添加異步操作來提高效率,所以下面這篇文章主要給大家介紹了關于spring?boot使用@Async注解解決異步多線程入庫問題的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下

前言

在開發(fā)過程中,我們會遇到很多使用線程池的業(yè)務場景,例如定時任務使用的就是ScheduledThreadPoolExecutor。而有些時候使用線程池的場景就是會將一些可以進行異步操作的業(yè)務放在線程池中去完成,例如在生成訂單的時候給用戶發(fā)送短信,生成訂單的結果不應該被發(fā)送短信的成功與否所左右,也就是說生成訂單這個主操作是不依賴于發(fā)送短信這個操作,所以我們就可以把發(fā)送短信這個操作置為異步操作。而要想完成異步操作,一般使用的一個是消息服務器MQ,一個就是線程池。今天我們就來看看在Java中常用的Spring框架中如何去使用線程池來完成異步操作,以及分析背后的原理。

在Spring4中,Spring中引入了一個新的注解@Async,這個注解讓我們在使用Spring完成異步操作變得非常方便。

在SpringBoot環(huán)境中,要使用@Async注解,我們需要先在啟動類上加上@EnableAsync注解。這個與在SpringBoot中使用@Scheduled注解需要在啟動類中加上@EnableScheduling是一樣的道理(當然你使用古老的XML配置也是可以的,但是在SpringBoot環(huán)境中,建議的是全注解開發(fā)),具體原理下面會分析。加上@EnableAsync注解后,如果我們想在調用一個方法的時候開啟一個新的線程開始異步操作,我們只需要在這個方法上加上@Async注解,當然前提是,這個方法所在的類必須在Spring環(huán)境中。

項目實況介紹

項目中,我需要將700w條數據,定時任務加入到mysql表中,去掉日志打印和一些其他因素的影響,入庫時間還是需要8個小時以上,嚴重影響后續(xù)的一系列操作,所以我才用@Async注解,來實現異步入庫,開了7個線程,入庫時間縮短為1.5個小時,大大提高效率,以下是詳細介紹,一級一些需要注意的坑.

需要寫個配置文件兩種方式

第一種方式

@Configuration
@EnableAsync //啟用異步任務
public class ThreadConfig {
    @Bean
    public ThreadPoolTaskExecutor executor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
          //配置核心線程數
        executor.setCorePoolSize(15);
          //配置最大線程數
        executor.setMaxPoolSize(30);
          //配置隊列大小
        executor.setQueueCapacity(1000);
          //線程的名稱前綴
        executor.setThreadNamePrefix("Executor-");
          //線程活躍時間(秒)
        //executor.setKeepAliveSeconds(60);
          //等待所有任務結束后再關閉線程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
          //設置拒絕策略
        //executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
          //執(zhí)行初始化
        executor.initialize();
        return executor;
    }
}

第二種方式

@Configuration
@EnableAsync
public class ExecutorConfig {

   @Value("${thread.maxPoolSize}")
   private Integer maxPoolSize;
   @Value("${thread.corePoolSize}")
   private Integer corePoolSize;
   @Value("${thread.keepAliveSeconds}")
   private Integer keepAliveSeconds;
   @Value("${thread.queueCapacity}")
   private Integer queueCapacity;
   @Bean
   public ThreadPoolTaskExecutor asyncExecutor(){
      ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
      taskExecutor.setCorePoolSize(corePoolSize);//核心數量
      taskExecutor.setMaxPoolSize(maxPoolSize);//最大數量
      taskExecutor.setQueueCapacity(queueCapacity);//隊列
      taskExecutor.setKeepAliveSeconds(keepAliveSeconds);//存活時間
      taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//設置等待任務完成后線程池再關閉
      taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//設置拒絕策略
      taskExecutor.initialize();//初始化
      return taskExecutor;
   }
}

配置文件

#線程池
thread:
  corePoolSize: 5
  maxPoolSize: 10
  queueCapacity: 100
  keepAliveSeconds: 3000

springboot默認是不開啟異步注解功能的,所以,要讓springboot中識別@Async,則必須在入口文件中,開啟異步注解功能

package com.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
 
//開啟異步注解功能
@EnableAsync
@SpringBootApplication
public class SpringbootTaskApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootTaskApplication.class, args);
    }
 
}

這里有個坑!

如果遇到報錯:需要加上    proxyTargetClass = true

The bean 'xxxService' could not be injected as a'com.xxxx.xxx.xxxService' because it is a JDK dynamic proxy that implements:
xxxxxx
Action:
Consider injecting the bean as one of its interfaces orforcing the use of CGLib-based proxiesby setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

當我service層處理完邏輯,吧list分成7個小list然后調用異步方法(異步方法的參數不用管,沒影響,只截取核心代碼)

List<List<DistributedPredictDTO>> partition = Lists.partition(userList, userList.size() / 7);
        for (List<DistributedPredictDTO> distributedPredictDTOS : partition) {
       //調用異步方法
            threadService.getI(beginDate, endDate, tableName, distributedPredictDTOS, hMap, i);
        }
@Slf4j
@Service
public class ThreadServiceImpl {
    @Resource
    ResourcePoolUrlProperties properties;
    @Resource
    private MonitorDao monitorDao;
    @Async
    Integer getI(String beginDate, String endDate, String tableName, List<DistributedPredictDTO> userList, Map<String, String> hMap, int i) {
        log.info("我開始執(zhí)行");
        for (DistributedPredictDTO e : userList) {
            String responseStr;
            HashMap<String, String> pMap = Maps.newHashMap();
            pMap.put("scheduleId", e.getScheduleId());
            pMap.put("scheduleName", e.getScheduleName());
            pMap.put("distribsunStationId", e.getLabel());
            pMap.put("distribsunStationName", e.getValue());
            pMap.put("beginTime", beginDate);
            pMap.put("endTime", endDate);
            try {
                if ("180".equals(properties.getNewPowerSys().getDistributedPredictUrl().substring(17, 20))) {
                    pMap = null;
                }
                responseStr = HttpClientUtil.doPost(properties.getNewPowerSys().getDistributedPredictUrl(), hMap, pMap);
            } catch (Exception exception) {
                throw new RuntimeException(e.getValue() + "的功率預測接口異常" + hMap + pMap);
            }
            if (org.springframework.util.StringUtils.isEmpty(responseStr)) {
                log.info(e + "數據為空");
                continue;
            }
            JSONObject resJson = JSONObject.parseObject(responseStr);
            JSONObject obj = (JSONObject) resJson.get("obj");
            JSONArray tableData = (JSONArray) obj.get("tabledata");

            final List<DistributedUserPower> userPowers = Lists.newArrayList();
            for (Object o : tableData) {
                final DistributedUserPower distributedUserPower = new DistributedUserPower();
                distributedUserPower.setData(((JSONObject) o).get("data").toString());
                distributedUserPower.setData2(((JSONObject) o).get("data2").toString());
                distributedUserPower.setDataTime(((JSONObject) o).get("time").toString());
                distributedUserPower.setUserId(e.getLabel());
                distributedUserPower.setUserName(e.getValue());
                distributedUserPower.setAreaName(e.getScheduleName());
                distributedUserPower.setCreateTime(DateUtils.getDate());
                userPowers.add(distributedUserPower);
            }
            monitorDao.saveBatch(userPowers, tableName);
            i++;
        }
        return i;
    }

這里有兩個坑!

第一個坑:

  我調用的異步方法在當前類中,則直接導致

@Async注解失效

正確操作,異步方法不要和同步調用方法寫在同一個類中,應該重新調用其他類

第二個坑:

如果出現這個報錯:

Null return value from advice does not mat

問題分析

代碼中采用異步調用,AOP 做來一層切面處理,底層是通過 JDK 動態(tài)代理實現

不管采用 JDK 還是 CGLIB 代理,返回值必須是包裝類型,所以才會導致上訴的報錯信息

處理方案

將異步方法的返回值修改為基本類型的對應包裝類型即可,如 int -> Integer

5分鐘測試效果圖:

最后一張是7線程:

總結

到此這篇關于spring boot使用@Async注解解決異步多線程入庫問題的文章就介紹到這了,更多相關springboot @Async異步多線程入庫內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java微服務實戰(zhàn)項目尚融寶接口創(chuàng)建詳解

    Java微服務實戰(zhàn)項目尚融寶接口創(chuàng)建詳解

    這篇文章主要介紹了Java微服務實戰(zhàn)項目尚融寶的接口創(chuàng)建流程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-08-08
  • Java?Optional的判空操作詳解

    Java?Optional的判空操作詳解

    JAVA在1.8版本推出Optional,官方文檔將其描述為可能包含或不包含非空值的容器對象,目前Optional用于避免程序出現異常NullPointerException,感興趣的可以了解一下
    2022-09-09
  • Java Web程序中利用Spring框架返回JSON格式的日期

    Java Web程序中利用Spring框架返回JSON格式的日期

    這里我們來介紹一下Java Web程序中利用Spring框架返回JSON格式的日期的方法,前提注意使用@DatetimeFormat時要引入一個類庫joda-time-版本.jar,否則會無法訪問相應路徑
    2016-05-05
  • PowerJob的OhMyClassLoader工作流程源碼解讀

    PowerJob的OhMyClassLoader工作流程源碼解讀

    這篇文章主要介紹了PowerJob的OhMyClassLoader工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • Java?不同版本的?Switch語句

    Java?不同版本的?Switch語句

    本文主要介紹了Java不同版本的Switch語句,自Java13以來,Switch表達式就被添加到Java核心庫中,下面我們將介紹舊的Java?Switch語句和新的Switch語句的區(qū)別,需要的朋友可以參考一下
    2022-06-06
  • Java Spring數據單元配置過程解析

    Java Spring數據單元配置過程解析

    這篇文章主要介紹了Java Spring數據單元配置過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-12-12
  • 解決MyBatis @param注解參數類型錯誤異常的問題

    解決MyBatis @param注解參數類型錯誤異常的問題

    這篇文章主要介紹了解決MyBatis @param注解參數類型錯誤異常的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • IntelliJ IDEA設置顯示內存指示器和設置內存大小的方法

    IntelliJ IDEA設置顯示內存指示器和設置內存大小的方法

    這篇文章主要介紹了IntelliJ IDEA設置顯示內存指示器和設置內存大小的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-04-04
  • 使用Spring?AOP實現用戶操作日志功能

    使用Spring?AOP實現用戶操作日志功能

    這篇文章主要介紹了使用Spring?AOP實現了用戶操作日志功能,功能實現需要一張記錄日志的log表,結合示例代碼給大家講解的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • idea中創(chuàng)建多module的maven工程的方法

    idea中創(chuàng)建多module的maven工程的方法

    這篇文章主要介紹了idea中創(chuàng)建多module的maven工程的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-10-10

最新評論