【juc】countdownlatch实现并发网络请求

news/2024/5/20 10:05:22 标签: juc

目录

        • 一、截图示例
        • 二、代码示例
          • 2.1 测试代码
          • 2.2 接口代码

一、截图示例

在这里插入图片描述
在这里插入图片描述

二、代码示例
2.1 测试代码
package com.learning.countdownlatch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author wangyouhui
 * @Description 异步查询信息
 **/
@Slf4j
public class Learning_03 {
    public static void main(String[] args) {
        test1();
        test2();
    }

    private static void test1() {
        System.out.println("查询信息开始");
        long begin = System.currentTimeMillis();
        log.info("开始时间: {}", begin);
        RestTemplate restTemplate = new RestTemplate();
        long start = System.currentTimeMillis();
        Map<String, Object> map = restTemplate.getForObject("http://127.0.0.1:8080/info/order/{1}", Map.class, 1);
        log.info("订单信息: {}, 耗时: {}", map, System.currentTimeMillis() - start);
        start = System.currentTimeMillis();
        map = restTemplate.getForObject("http://127.0.0.1:8080/info/product/{1}", Map.class, 1);
        log.info("产品1信息: {}, 耗时: {}", map, System.currentTimeMillis() - start);
        start = System.currentTimeMillis();
        map = restTemplate.getForObject("http://127.0.0.1:8080/info/product/{1}", Map.class, 2);
        log.info("产品2信息: {}, 耗时: {}", map, System.currentTimeMillis() - start);
        start = System.currentTimeMillis();
        map = restTemplate.getForObject("http://127.0.0.1:8080/info/package/{1}", Map.class, 1);
        log.info("快递信息: {}, 耗时: {}", map, System.currentTimeMillis() - start);
        long end = System.currentTimeMillis();
        log.info("结束时间: {}", end);
        log.info("查询信息结束, 总耗时: {}", end-begin);
    }

    private static void test2() {
        System.out.println("查询信息开始");
        long begin = System.currentTimeMillis();
        log.info("开始时间: {}", begin);
        CountDownLatch countDownLatch = new CountDownLatch(4);
        ExecutorService executorService = Executors.newCachedThreadPool();
        RestTemplate restTemplate = new RestTemplate();
        executorService.submit(()->{
            long start = System.currentTimeMillis();
            Map<String, Object> map = restTemplate.getForObject("http://127.0.0.1:8080/info/order/{1}", Map.class, 1);
            log.info("订单信息: {}, 耗时: {}", map, System.currentTimeMillis() - start);
            countDownLatch.countDown();
        });
        executorService.submit(()->{
            long start = System.currentTimeMillis();
            Map<String, Object> map = restTemplate.getForObject("http://127.0.0.1:8080/info/product/{1}", Map.class, 1);
            log.info("产品1信息: {}, 耗时: {}", map, System.currentTimeMillis() - start);
            countDownLatch.countDown();
        });
        executorService.submit(()->{
            long start = System.currentTimeMillis();
            Map<String, Object> map = restTemplate.getForObject("http://127.0.0.1:8080/info/product/{1}", Map.class, 2);
            log.info("产品2信息: {}, 耗时: {}", map, System.currentTimeMillis() - start);
            countDownLatch.countDown();
        });
        executorService.submit(()->{
            long start = System.currentTimeMillis();
            Map<String, Object> map = restTemplate.getForObject("http://127.0.0.1:8080/info/package/{1}", Map.class, 1);
            log.info("快递信息: {}, 耗时: {}", map, System.currentTimeMillis() - start);
            countDownLatch.countDown();
        });
        // 主线程等待
        try{
            countDownLatch.await();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        executorService.shutdown();
        long end = System.currentTimeMillis();
        log.info("结束时间: {}", end);
        log.info("查询信息结束, 总耗时: {}", end-begin);
    }
}

2.2 接口代码
package com.learning.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Author wangyouhui
 * @Description TODO
 **/
@RestController
@RequestMapping("info")
@Slf4j
public class InfoController {
    @GetMapping("/order/{id}")
    public Map<String, Object> orderDetail(@PathVariable Long id){
        log.info("开始查找订单: {}", id);
        try {
            Random random = new Random();
            Thread.sleep(2000 + random.nextInt(2000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("id", id);
        result.put("total", 1300);
        log.info("查找订单结束: {}", id);
        return result;
    }

    @GetMapping("/product/{id}")
    public Map<String, Object> productDetail(@PathVariable Long id){
        log.info("开始查找产品: {}", id);
        try {
            Random random = new Random();
            Thread.sleep(500 + random.nextInt(2000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap<>();
        if(id == 1){
            result.put("id", id);
            result.put("price", 300);
            result.put("name", "小米耳机");
        }else{
            result.put("id", id);
            result.put("price", 1000);
            result.put("name", "三星硬盘");
        }
        log.info("开始查找产品: {}", id);
        return result;
    }

    @GetMapping("/package/{id}")
    public Map<String, Object> packageDetail(@PathVariable Long id){
        log.info("开始查找快递: {}", id);
        try {
            Random random = new Random();
            Thread.sleep(3000 + random.nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("id", id);
        result.put("name", "中通快递");
        result.put("id", id);
        log.info("开始查找快递: {}", id);
        return result;
    }
}


http://www.niftyadmin.cn/n/5071410.html

相关文章

【思维构造】Circle of Monsters—CF1334C

Circle of Monsters—CF1334C 思路 每一个怪兽都有两种死法&#xff1a; 直接被子弹打死先被上一个怪兽爆炸击伤&#xff0c;剩下的血量再用子弹打死 所以&#xff0c;很容易看出来第二种死法对于所有的怪兽都是最优死法&#xff08;消耗子弹最少的死法&#xff09;。我们需要…

解决ubuntu中没有网络连接的图标

现象&#xff1a;Ubuntu连接网络 在设置中没有显示网络图标 解决方案&#xff1a; 命令为 sudo nmcli networking off sudo nmcli networking on sudo service network-manager restart 重启ubuntu&#xff0c;网络连接完成

10-Node.js入门

01.什么是 Node.js 目标 什么是 Node.js&#xff0c;有什么用&#xff0c;为何能独立执行 JS 代码&#xff0c;演示安装和执行 JS 文件内代码 讲解 Node.js 是一个独立的 JavaScript 运行环境&#xff0c;能独立执行 JS 代码&#xff0c;因为这个特点&#xff0c;它可以用来…

JVM(八股文)

目录 一、JVM简介 二、JVM中的内存区域划分 三、JVM加载 1.类加载 1.1 加载 1.2 验证 1.3 准备 1.4 解析 1.5 初始 1.6 总结 2.双亲委派模型 四、JVM 垃圾回收&#xff08;GC&#xff09; 1.确认垃圾 1.1 引用计数 1.2 可达性分析&#xff08;Java 采用的方案&a…

08 集群参数配置(下)

Kafka Broker不需要太大的堆内存&#xff1f; Kafka Broker不需要太大的堆内存&#xff1f;应该把内存留给页缓存使用&#xff1f; kafka刷盘时宕机 kafka认为写入成功是指写入页缓存成功还是数据刷到磁盘成功算成功呢&#xff1f;还是上次刷盘宕机失败的问题&#xff0c;页…

C语言之共用体、枚举类型、typedef

共用体 共用体的所有成员共享同一个内存地址 插入一个知识点&#xff1a;字符串不可以直接赋值&#xff0c;要不就在定义的时候赋值&#xff0c;要不就只能使用scanf函数赋值或者<string>中的strcpy赋值 证明 如果要同时访问联合体中多个成员的值...... 则会出现以下情…

跨境电商系统对接-进口

一、跨境进口方式 1、一般贸易 指中国境内有进出口经营权的企业进行进出口贸易&#xff0c;货物到港后需要先清关&#xff08;办理海关申报、查验、征税、放行等手续&#xff09;&#xff0c;然后货主才能提货&#xff0c;一般贸易适合大批量进口商品&#xff0c;公司的鲜奶、…

VS2022+QT使用VTK教程

使用VTK库 说明&#xff1a;使用VTK库之前&#xff0c;VTK环境必须要配置成功&#xff0c;配置VTK教程&#xff1a;https://blog.csdn.net/HXX904/article/details/133639010 配置成功的小伙伴们就可以往下去看如何使用VTK。 需要用到的文件&#xff0c;这些文件来源在配置V…