springboot使用线程池实现异步调用

1.启动类添加支持异步调用的注解

package com.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.springboot.mapper")
@EnableAsync//支持异步的注解
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

2.线程池配置

package com.springboot.threadpool;

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;

@Configuration
@EnableAsync
public class ThreadPoolConfig {

    // 获取服务器的cpu个数
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();// 获取cpu个数
    private static final int COUR_SIZE = CPU_COUNT * 2;
    private static final int MAX_COUR_SIZE = CPU_COUNT * 4;

    // 接下来配置一个bean,配置线程池。
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(COUR_SIZE);// 设置核心线程数
        threadPoolTaskExecutor.setMaxPoolSize(MAX_COUR_SIZE);// 配置最大线程数
        threadPoolTaskExecutor.setQueueCapacity(MAX_COUR_SIZE * 4);// 配置队列容量(这里设置成最大线程数的四倍)
        threadPoolTaskExecutor.setThreadNamePrefix("ThreadPoolTaskExecutor-");// 给线程池设置名称前置
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 设置任务的拒绝策略
        return threadPoolTaskExecutor;
    }
}

3.具体使用如下

package com.springboot.threadpool;

public interface TestService {
    void testService();
}

package com.springboot.threadpool;

import com.springboot.mapper.AdminMapper;
import com.springboot.mapper.EmployeeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


/**
testService模拟了异常
 */
@Service
public class TestServiceImpl implements TestService {

    private static final Logger logger = LoggerFactory.getLogger("TestService");

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    @Async("threadPoolTaskExecutor")// 提交到线程池中去处理
    public void testService() {
        logger.info("start service");
        try {
            Thread.sleep(100000);
           logger.info("怒发冲冠,凭栏处,潇潇雨歇,抬望眼,仰天长啸,壮怀激烈,三十功名尘与土,八千里路云和月,莫等闲,白了少年头,空悲切。" +
                   "靖康耻,犹未雪,臣子恨,何时灭,驾长车,踏破贺兰山缺,壮志饥餐胡虏肉,笑谈渴饮匈奴血,待从头,收拾旧山河,朝天阙");
            logger.info("");
            int t=5/0;
            employeeMapper.getAllEpmloyee(null);
            adminMapper.getAllAdmin(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("end service");
    }
}

package com.springboot.threadpool;

import com.springboot.errutil.ReturnMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
public class ThreadPoolController {

    private final Logger logger = LoggerFactory.getLogger("ThreadPoolController");

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private TestService testService;

    @GetMapping("/thread")
    public ReturnMsg testThread() {
        threadPoolTaskExecutor.execute(() -> {
            try {
                Thread.sleep(10000);// 为了演示方便,让变成休眠10秒
                logger.info("执行线程池任务");
                logger.info(Thread.currentThread().getName());//打印线程名称
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });// 需要传递Runnable对象
        logger.info("主线程名称:{}", Thread.currentThread().getName());//再打印主线程名称
        return new ReturnMsg(true, "0000", Thread.currentThread().getName(), Thread.currentThread().getName());
    }


    @GetMapping("/threadTervice")
    public ReturnMsg threadTervice() throws InterruptedException {
        logger.info("start controller");
       long beginTime=System.currentTimeMillis();
        testService.testService();
        logger.info("end controller");
        long endTIme = System.currentTimeMillis();
        logger.info("threadTervice执行了{}ms",endTIme-beginTime);
        return new ReturnMsg(true, "0000", Thread.currentThread().getName(), Thread.currentThread().getName());
    }
}

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值