基于线程池的多线程查询功能

package com.changshin.threadpool;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPool {
    /**
     * 连接池
     */
    private ExecutorService pool;

    @PostConstruct
    public void afterPropertiesSet() {
        pool = Executors.newFixedThreadPool(50);
    }

    public List<OtherServerResponse> test(List testList) {
        List<Future<OtherServerResponse>> futureList = new ArrayList<Future<OtherServerResponse>>();
        int tolSize = testList.size();
        CountDownLatch countDownLatch = new CountDownLatch(10);//计数器
        for (int i = 0; i < tolSize; i++) {
            long num = (tolSize - countDownLatch.getCount()) * 50L;
            futureList.add(pool.submit(() -> {
                Thread.sleep(num);//对线程进行睡眠避免对调用服务造成压力
                OtherServerResponse response = new OtherServerResponse();//模拟对其他接口调用,返回信息
                System.out.println("执行对其他微服务接口调用");
                return response;
            }));
        }
        long rpcTimeout = 60L;//设置超时时间
        List<OtherServerResponse> newList = new ArrayList<OtherServerResponse>();
        for (Future<OtherServerResponse> future : futureList) {
            try {
                OtherServerResponse bean = future.get(rpcTimeout, TimeUnit.SECONDS);
                newList.add(bean);
            } catch (Throwable e) {
                System.out.println("调用rpc异常");
                throw new RuntimeException("调用rp异常");
            }
        }
        return newList;
    }


}

       最近接到一个任务需要查询一个一个客户的交易列表,但是交易列表查询回来后,返回的字段不满足要求,需要根据列表子对象的id调用一个接口查询接口的详细信息。如果数据量大影响导致返回的速度。这里启用线程查询,节省了时间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值