CountDownLatch和okhttp3 实现多线程异步http调用

本文介绍了如何在实际工作中利用CountDownLatch进行多线程异步调用,以提高第三方接口或其他耗时任务的响应速度。通过伪代码和具体实现展示了okhttp3配置及异步调用逻辑,从而实现时间效率的提升。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、在工作中需要多次调用第三方接口,或者其他耗时任务,这个时候为了提高返回结果的速度,可以利用countDownLatch来实现多线程调用,提高返回结果的时间。

(1) 由于代码较多,这里先将实现逻辑由伪代码,先行演示一遍。

//先定义需要异步调用的次数,每次调用 CountDownLatch.countDown();
//等最慢的一次完成调用,封装在list对象里面,这个时候 CountDownLatch 减为0继续往下进行
@Autowired
private AsyncTask asyncTask;

 CountDownLatch countDownLatch = new CountDownLatch(4);
        List<TbOrder> tbOrders = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            asyncTask.doTaskOne(tbOrders, i,countDownLatch);
        }
        countDownLatch.await(10, TimeUnit.SECONDS);

异步伪代码

@EnableAsync
@Component
public class AsyncTask {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private HttpClient httpClient;

    @Async
    public void doTaskOne(List<TbOrder> users, int i, CountDownLatch countDownLatch) throws Exception {
     List<TbOrder>  orders=doPost();
     users.addl(orders);
      ccountDownLatch.countDown();
    }
}

(2)下面是具体的实现
(下面是需要用到maven依赖)

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>

(关于okhttp3 连接的配置)

ok.http.connect-timeout=30
ok.http.read-timeout=30
ok.http.write-timeout=30
# 连接池中整体的空闲连接的最大数量
ok.http.max-idle-connections=200
# 连接空闲时间最多为 300 秒
ok.http.keep-alive-duration=300

(关于okhttp3 初始化OkHttpClient 的配置)

@Configuration
public class OkHttpConfiguration {

    @Value("${ok.http.connect-timeout}")
    private Integer connectTimeOut;

    @Value("${ok.http.read-timeout}")
    private Integer readTimeOut;

    @Value("${ok.http.write-timeout}")
    private Integer writeTimeOut;


    @Value("${ok.http.max-idle-connections}")
    private Integer maxIdle
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值