springboot线程池配置插入数据库数据
1创建ExecutorConfig,配置线程池
package com.example.hcmall.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ExecutorConfig {
private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
@Bean
public Executor asyncServiceExecutor() {
logger.info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(10);
//配置最大线程数
executor.setMaxPoolSize(10);
//配置队列大小
executor.setQueueCapacity(99999);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("Thread-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
2、注解式线程(Async)
@Override
@Async("asyncServiceExecutor")
public Future<Integer> addcar(Bean bean) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String userid = bean.getUserid();
String productid = bean.getProductid();
String time = df.format(new Date());
String fhadress = bean.getFhadress();
String shadress = bean.getShadress();
String phone = bean.getPhone();
Order order = new Order();
bean.setStatus(0);
bean.setTime(time);
logger.info(Thread.currentThread().getName());
return new AsyncResult<>(orderDao.insertorder(bean));
}
注意启动类要加EnableAsync可以使用多线程
下面上图对比
不使用线程时
使用线程是
controller(我的测试方法)
@PostMapping("/addcar")
public Returnrestful addcar(Bean bean) throws ExecutionException, InterruptedException {
long startTime = System.currentTimeMillis();
List list = new ArrayList();
for (int i = 0; i < 100; i++) {
orderService.addcar(bean);
list.add(orderService.addcar(bean).get());
}
long endTime = System.currentTimeMillis();
System.out.println("耗时 : " + (endTime - startTime));
if (list.size() >= 1) {
return new Returnrestful(Resultconfig.SUCCESS.getCode(), Resultconfig.SUCCESS.getMsg(), Resultconfig.SUCCESS.getMsg(), "添加成功");
} else {
return new Returnrestful(Resultconfig.FAIL.getCode(), Resultconfig.FAIL.getMsg(), Resultconfig.FAIL.getMsg(), "添加失败");
}
}