異步上傳,數據從1萬提高到5萬

1、配置文件yaml :java

task:
core:
poolsize: 100
max:
poolsize: 200
queue:
capacity: 200
keepAlive:
seconds: 30
thread:
name:
prefix: msgcenterspring

2、java 代碼配置異步

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;br/>@Configuration
@EnableAsync
public class AsyncConfig {ide

//接收報文核心線程數
@Value("${task.core.poolsize}")
private int taskCorePoolSize;
//接收報文最大線程數
@Value("${task.max.poolsize}")
private int taskMaxPoolSize;
//接收報文隊列容量
@Value("${task.queue.capacity}")
private int taskQueueCapacity;
//接收報文線程活躍時間(秒)
@Value("${task.keepAlive.seconds}")
private int taskKeepAliveSeconds;
//接收報文默認線程名稱
@Value("${task.thread.name.prefix}")
private String taskThreadNamePrefix;

/**
 * bookTaskExecutor:(接口的線程池). <br/>
 *
 * @return TaskExecutor taskExecutor接口
 * @since JDK 1.8
 */
@Bean()
public ThreadPoolTaskExecutor bookTaskExecutor() {
    //newFixedThreadPool
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    // 設置核心線程數
    executor.setCorePoolSize(taskCorePoolSize);
    // 設置最大線程數
    executor.setMaxPoolSize(taskMaxPoolSize);
    // 設置隊列容量
    executor.setQueueCapacity(taskQueueCapacity);
    // 設置線程活躍時間(秒)
    executor.setKeepAliveSeconds(taskKeepAliveSeconds);
    // 設置默認線程名稱
    executor.setThreadNamePrefix(taskThreadNamePrefix);
    // 設置拒絕策略
    // rejection-policy:當pool已經達到max size的時候,如何處理新任務
    // CALLER_RUNS:不在新線程中執行任務,而是由調用者所在的線程來執行
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    // 等待全部任務結束後再關閉線程池
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.initialize();
    return executor;

}

}線程

3、異步方法,添加@Async() 註解code

@Async() 
@Override
public void addAppExceldata(List<AppointUploadUserVo> list, String taskId, int type) throws Exception {

    }
}
    以上方法從一萬上傳效率提高到5萬 ,而且在一分鐘只能請求接口不超時。
相關文章
相關標籤/搜索