栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot多线程请求数据接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot多线程请求数据接口

一、yml配置

#多线程配置
mythreadpool:
  maxPoolSize: 20
  corePoolSize: 8
  queueCapacity: 2048
  keepAliveSeconds: 60
  threadNamePrefix: springThreadPool
  waitForTasksToCompleteOnShutdown: true

二、配置类

@Configuration
@EnableAsync
public class MyThreadPoolConfig {

    
    @Bean("myThreadPool")
    public Executor threadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数:线程池创建时候初始化的线程数
        executor.setCorePoolSize(10);
        // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(20);
        // 缓冲队列:用来缓冲执行任务的队列
        executor.setQueueCapacity(500);
        // 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
        executor.setThreadNamePrefix("do-ocr-");
        // 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程)
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.initialize();
        return executor;
    }

}

三、专门写一个异步线程执行的spring组件类

@Component
public class AsyncRequestComponent {

    @Autowired
    MongoTemplate mongoTemplate;

    @Async("myThreadPool")
    public CompletableFuture mockHttpRequest(String imageUrl){
        String threadName = Thread.currentThread().getName();
        System.out.println("线程" + threadName + "开始调用,输出:" + imageUrl);
        String result = "";

        Test test = new Test();
        try {
            result = XxxUtil.requestUrl(imageUrl);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject invoiceJsonObject = mongoTemplate.insert(jsonObject);
	        test = t.setName("测试");

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("线程" + threadName + "调用结束,输出:" + imageUrl);
        return CompletableFuture.completedFuture(test);
    }
}

四、controller层

    @ApiOperation("测试")
    @RequestMapping("/test")
    public R test(@RequestBody TestDto testDto){

        List> listOfFuture = new ArrayList<>();

        List testDto =new ArrayList();

        for (int i =0;i
            CompletableFuture completableFuture = asyncOcr.mockHttpRequest(disImages.getImgs()[i]);
            listOfFuture.add(completableFuture);
        }

        //必须想办法阻塞,直到所有线程返回结果了
        CompletableFuture result = CompletableFuture.allOf(listOfFuture.toArray(new CompletableFuture[listOfFuture.size()]));

        CompletableFuture> listCompletableFuture = result.thenApply(v ->
                listOfFuture.stream().map(CompletableFuture::join).collect(Collectors.toList()));

        try {
            testDto = listCompletableFuture.get();
            logger.info(testDto.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok(testDto);
    }

相关注解和方法
@EnableAsync
@Async(“myThreadPool”)
CompletableFuture
CompletableFuture.allOf()
CompletableFuture.get()
Thread.currentThread().getName() 获得当前线程名字

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/939353.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号