SpringBoot ThreadPoolExecutor实现多线程

利用spring ThreadPoolExecutor实现多线程

处理高耗时任务时,使用多线程可以提高效率。

创建线程池

@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean("taskExecutor")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数5:线程池创建时候初始化的线程数
        executor.setCorePoolSize(5);
        //最大线程数5:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(5);
        //缓冲队列500:用来缓冲执行任务的队列
        executor.setQueueCapacity(500);
        //允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        //线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix("ExecutorThread-");
        executor.initialize();
        return executor;
    }
}

使用线程池

@Service
public class InfoService {
    private InfoDao infoDao;
    @Autowired
    public InfoService(InfoDao infoDao){
        this.infoDao = infoDao;
    }
    //标注为异步任务,用线程池执行
    @Async("taskExecutor")
    //异步方法返回类型要求为CompletableFuture
    public CompletableFuture<Info> getInfoById(int id){
    	//假设这个方法执行5秒
        try {
            Thread.sleep(5000);
        }catch (Exception e){
        }
        return CompletableFuture.completedFuture(infoDao.getInfoById(id));
    }
}

测试

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class AsyncTest {
    private static final Logger logger = LoggerFactory.getLogger(AsyncTest.class);
    @Autowired
    private InfoService infoService;
    @Test
    public void asyncTest() throws InterruptedException, ExecutionException {
        // Start the clock
        long start = System.currentTimeMillis();
        CompletableFuture<Info> info1 = infoService.getInfoById(1);
        CompletableFuture<Info> info2 = infoService.getInfoById(1);
        CompletableFuture<Info> info3 = infoService.getInfoById(1);
        CompletableFuture<Info> info4 = infoService.getInfoById(1);
        CompletableFuture<Info> info5 = infoService.getInfoById(1);
        // Wait until they are all done
        CompletableFuture.allOf(info1,info2,info3,info4,info5).join();
        // Print results, including elapsed time
        float exc = (float)(System.currentTimeMillis() - start)/1000;
        logger.info("Elapsed time: " + exc + " seconds");
    }
}

执行测试,多线程大大缩短了执行时间。
AsyncTest

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中实现文件上传的多线程可以通过以下步骤完成: 1. 创建一个文件上传的Controller,用于处理文件上传请求。可以使用`@RestController`注解进行标记。 2. 在Controller中创建一个`@PostMapping`方法来处理文件上传的请求。该方法应该接受一个`MultipartFile`类型的参数,于接收上传的文件。 3. 在方法内部,创建一个线程池,可以使用`ThreadPoolExecutor`来实现。示例代码如下: ```java ExecutorService executorService = Executors.newFixedThreadPool(5); ``` 4. 使用线程池提交任务,将文件上传的逻辑放在一个线程中执行。示例代码如下: ```java executorService.submit(() -> { // 文件上传逻辑 }); ``` 5. 在文件上传的逻辑中,可以使用Java的IO操作来将文件保存到指定位置。示例代码如下: ```java try (InputStream inputStream = file.getInputStream(); OutputStream outputStream = new FileOutputStream("保存文件的路径")) { // 读取上传文件的内容,并写入到输出流中 byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { // 处理异常情况 } ``` 6. 最后,在Controller方法中返回适当的响应,表示文件上传成功或失败。 需要注意的是,多线程上传文件可能会面临一些并发访问的问题,例如同名文件的覆盖等。可以根据具体需求来设计并发控制的策略,以确保文件上传的安全和正确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值