springBoot线程池使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xm526489770/article/details/83510454

在我们现实开发中肯定会遇到需要延时请求并且高并发的业务场景,所以结合这个我自己写了一个模拟延时+高并发的小案例供大家参考.

1. 线程池相关配置(当然你也可以写在配置文件中方便改动,我就先写死了):

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class BeanConfig {

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("hello-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

2. 要进行延时处理并且高并发的业务代码:

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
public class Test {

    @Async
   public void test(int i){
        SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
        try {
            Thread.sleep(10000);
            System.out.println("多线程异步执行"+i+"  "+Thread.currentThread().getName()+"  "+format.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}

3.模拟多个页面请求后要进行后续逻辑处理:

@GetMapping("/test1")
@ResponseBody
public void test1(){
    for (int i = 0; i < 100; i++) {
         test.test(i);

    }

}

4.执行结果,我设置线程池大小为10,业务执行逻辑开始时休眠10秒再执行,你会发现每10秒就会有10个线程开始执行业务:

猜你喜欢

转载自blog.csdn.net/xm526489770/article/details/83510454