SpringBoot线程池异步调用

本文介绍了在SpringBoot中配置和使用线程池的三种方法,包括直接使用自动装配的线程池、自定义线程池配置以及覆盖默认配置。并展示了通过@Async注解实现异步任务的提交过程,详细解释了Controller、Service和ServiceImpl的实现细节,强调了提高并发处理能力的应用场景。

目录

一、装配线程池的三种方法

1、直接使用SpringBoot框架自动装配的线程池

2、SpringBoot配置线程池

3、覆盖SpringBoot自动配置的线程池,使用自定义的线程池

二、使用SpringBoot框架自动装配的线程池,提交任务采用@Async注解的过程

1、Controller

2、Service

3、ServiceImpl【直接加@Async注解】


一、装配线程池的三种方法

1、直接使用SpringBoot框架自动装配的线程池

SpringBoot框架自动装配提供了一个的线程池,用于提交异步任务;

有了线程池我们就只需要写任务即可,提交任务采用@Async注解;(底层是aop)

2、SpringBoot配置线程池

#SpringBoot配置线程池,修改线程池默认配置
spring.task.execution.pool.max-size=99999
spring.task.execution.thread-name-prefix=cat-task-
spring.task.execution.pool.queue-capacity=99999

3、覆盖SpringBoot自动配置的线程池,使用自定义的线程池

我们也可以覆盖SpringBoot自动配置的线程池,用我们自定义的线程池:

@Bean
public ThreadPoolTaskExecutor asyncExecutor() {


 logger.info("start asyncExecutor......");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    //配置核心线程数
    executor.setCorePoolSize(16);
    //配置最大线程数
    executor.setMaxPoolSize(64);
    //配置队列大小
    executor.setQueueCapacity(9999);
    //配置线程池中的线程的名称前缀
    executor.setThreadNamePrefix("async-order-");
    // rejection-policy:当pool已经达到max pool size的时候,如何处理新任务
    // CALLER_RUNS:不在新线程中执行任务,而是由调用线程(提交任务的线程)处理该任务
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    //执行初始化
    executor.initialize();
    return executor;
}

二、使用SpringBoot框架自动装配的线程池,提交任务采用@Async注解的过程

1、Controller

package com.bjpowernode.controller;

import com.bjpowernode.service.AsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

@RestController
public class AsyncController {

    private static final Logger logger = LoggerFactory.getLogger(AsyncController.class);

    @Autowired
    private AsyncService asyncExecutorService;

    @RequestMapping("/async")
    public Object async() throws ExecutionException, InterruptedException {
        System.out.println("start submit");

        //调用service层的异步任务
        //(发短信,要发10几万短信,为了提高发短信的效率,所以可以把发短信用线程池执行,同时可以有多个线程在执行发短信)
        //Future<String> future = asyncExecutorService.sendSMS();
        //Object result = asyncExecutorService.sendSMS();

        CountDownLatch countDownLatch = new CountDownLatch(3);

        List<List<String>> lists = new ArrayList<>();

        List<String> list1 = new ArrayList<>();
        list1.add("1-01");
        list1.add("1-02");
        list1.add("1-03");

        List<String> list2 = new ArrayList<>();
        list2.add("2-01");
        list2.add("2-02");
        list2.add("2-03");

        List<String> list3 = new ArrayList<>();
        list3.add("3-01");
        list3.add("3-02");
        list3.add("3-03");

        lists.add(list1);
        lists.add(list2);
        lists.add(list3);

        //线程数为分批插入数据数
        for (int i = 0; i < lists.size(); i++) {
            List<String> insert = lists.get(i);
            System.out.println("插入数据" + (i + 1) + "正在更新HF数据库,共" + lists.size() + "个片段, 每片" + insert.size() +"条数据");
            asyncExecutorService.sendSMS(insert, countDownLatch);
        }
        countDownLatch.await();

        System.out.println("end submit");

        return "OK";
    }
}

2、Service

package com.bjpowernode.service;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public interface AsyncService {

    //public Future<String> sendSMS ();

    //public Object sendSMS();

    public void sendSMS(List<String> list, CountDownLatch countDownLatch);
}

3、ServiceImpl【直接加@Async注解】

package com.bjpowernode.service.impl;

import com.bjpowernode.service.AsyncService;
import com.bjpowernode.sms.SMS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
public class AsyncServiceImpl implements AsyncService {

    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Autowired
    private ThreadPoolTaskExecutor applicationTaskExecutor;

    @Async
    @Override
    public void sendSMS(List<String> list, CountDownLatch countDownLatch) {
        System.out.println("start executeAsync......");
        int sum = 0;
        for (int i=0; i<list.size(); i++) {
            //System.out.println(list.get(i));
            String result = SMS.sendSMS("恭喜您获得15天VIP体验资格.");
            sum ++;
        }
        System.out.println("线程-" + Thread.currentThread().getId() + "导入完成"+sum+"条数据");
        System.out.println("end executeAsync......");
        countDownLatch.countDown();
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值