springboot中使用@Async + CountDownLatch + Future

话不多说看代码,注释都在代码里,一看就懂。

【文中其实对于有返回值的线程任务,没有必要使用coutDownLatch 了,因为 future.get()就是个阻塞方法,会挂起主线程,直到该子线程执行结束。 如果使用没有返回值的子线程,而且需要等待多个子线程执行完成,那么可以考虑使用CountDownLatch来控制】

1. 用到的代码文件如下:

2. 开始贴代码:

  ① controller:就一个简单的请求,调用service,主要逻辑在service层

@RestController
@Slf4j
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/test004")
    public ArrayList<String> testAsyncFeedBack() throws Exception {
        return testService.testAsyncFeedBack();
    }
}

② service:模拟了使用三个子线程去执行任务,详细看注释(写代码不注释,写了个寂寞)

package com.example.demo.service;

import com.example.demo.entity.FutureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TestService {
    @Autowired
    private ApplicationContext applicationContext;

    public ArrayList<String> testAsyncFeedBack() throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        //这里展示了一种方法,可用于在一个类中调用标注有@async 或者 @transactional等基于aop的注解的方法,并使注解生效
        //这个 TestService.class 就是当前类
        //applicationContext 直接@autowire注入进来就行
        TestService proxyService = applicationContext.getBean(TestService.class);
        List<String> nameList = new ArrayList<>();
        Future<FutureResult<List<String>>> future1 = proxyService.getNameList(nameList, countDownLatch);

        List<String> addressList = new ArrayList<>();
        Future<FutureResult<List<String>>> future2 = proxyService.getAddressList(addressList, countDownLatch);

        List<String> numberList = new ArrayList<>();
        Future<FutureResult<List<String>>> future3 = proxyService.getNumberList(numberList, countDownLatch);

        //等待子线程执行完毕
        countDownLatch.await();
        //三个子线程全部正常执行,才给接口调用方返回数据,否则抛出异常(各位可根据看情况是否需要这么做)
        if (future3.get().getStatus() == 1 && future3.get().getStatus() == 1 && future3.get().getStatus() == 1) {
            ArrayList<String> respList = new ArrayList<>();
            respList.addAll(future1.get().getData());
            respList.addAll(future2.get().getData());
            respList.addAll(future3.get().getData());
            log.info("main 线程执行完毕");
            return respList;
        } else {
            log.info("main 线程执行完毕");
            throw new Exception("多线程处理发生异常");//这里只是简单的new了一个异常,各位看官根据自己业务处理
        }
    }

    @Async("asyncServiceExecutor")
    public Future<FutureResult<List<String>>> getNumberList(List<String> numberList, CountDownLatch countDownLatch) {
        log.info("getNumberList...");
        FutureResult<List<String>> listFutureResult = new FutureResult<>();//自己定义了一个future的返回的结果
        ArrayList<String> strings = new ArrayList<>();
        listFutureResult.setData(strings);
        try {
            strings.add("number");
            TimeUnit.SECONDS.sleep(10);//模拟耗时业务代码
            // 模拟异常情况
//            int a = 1 / 0;
            listFutureResult.setStatus(1); //如果正常执行完业务代码,这里就设置状态为1
            log.info("getNumberList 执行完了");
        } catch (Exception e) {
            log.error("getNumberList error...", e);
            listFutureResult.setStatus(0); //如果执行业务代码发生异常,这里就设置状态为0
            listFutureResult.setException(e);//如果需要异常信息,也可在此处把异常塞回去
        } finally {
            //最终不管该子线程是否抛出异常一定要调用countDown方法,要不然主线程会一直等待这个子线程调用countDown
            countDownLatch.countDown();
        }
        return new AsyncResult<>(listFutureResult);
    }

    @Async("asyncServiceExecutor")
    public Future<FutureResult<List<String>>> getAddressList(List<String> addressList, CountDownLatch countDownLatch) {
        log.info("getAddressList...");
        FutureResult<List<String>> listFutureResult = new FutureResult<>();
        ArrayList<String> strings = new ArrayList<>();
        listFutureResult.setData(strings);
        try {
            strings.add("address");
            TimeUnit.SECONDS.sleep(7); //模拟耗时业务代码
            listFutureResult.setStatus(1);
            countDownLatch.countDown();
            log.info("getAddressList 执行完了");
        } catch (Exception e) {
            log.error("getAddressList error...", e);
            listFutureResult.setStatus(0);
            listFutureResult.setException(e);
        } finally {
            countDownLatch.countDown();
        }
        return new AsyncResult<>(listFutureResult);
    }

    @Async("asyncServiceExecutor")
    public Future<FutureResult<List<String>>> getNameList(List<String> nameList, CountDownLatch countDownLatch) {
        log.info("getNameList start...");
        FutureResult<List<String>> listFutureResult = new FutureResult<>();
        ArrayList<String> strings = new ArrayList<>();
        listFutureResult.setData(strings);
        try {
            strings.add("name");
            TimeUnit.SECONDS.sleep(3);//模拟耗时业务代码
            listFutureResult.setStatus(1);
            countDownLatch.countDown();
            ;
            log.info("getNameList 执行完了");
        } catch (Exception e) {
            log.error("getNameList error...", e);
            listFutureResult.setStatus(0);
            listFutureResult.setException(e);
        } finally {
            countDownLatch.countDown();
        }
        return new AsyncResult<>(listFutureResult);
    }
}

 ③自定义的FutureResult 类,用于满足自己的需求,方便查看子线程的状态,以及子线程执行结果

package com.example.demo.entity;

import lombok.Data;

@Data
public class FutureResult<T> {
    private int status;
    private T data;
    private Exception exception;
}

④自定义线程池:TaskPoolConfig, 如何自定义线程池,各看官可再行研究

package com.example.demo.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@ConfigurationProperties(prefix = "task-pool")
@Slf4j
@Data
public class TaskPoolConfig {
    private int coreSize;
    private int keepAlive;
    private int maxSize;
    private int queueCapacity;

    @Bean("asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        log.info("coreSize:{},keepAlive:{},maxSize:{},queueCapacity:{}", coreSize, keepAlive, maxSize, queueCapacity);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coreSize);
        executor.setMaxPoolSize(maxSize);
        executor.setKeepAliveSeconds(keepAlive);
        executor.setQueueCapacity(queueCapacity);
        executor.setAwaitTerminationSeconds(60);
        executor.setThreadNamePrefix("my-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

⑤application.yml:

server:
  port: 8081
task-pool:
  core-size: 10
  keep-alive: 60
  max-size: 10
  queue-capacity: 1000

3. 至此完毕!请享用。。。如果帮到了你,那就来个赞,不喜轻喷。。。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值