1.需求说明
1.1 同一款产品,同时搜索出同款产品在各大电商平台的售价;
1.2 同一款产品,同时搜索出本产品在同一个电商平台下,各个入驻卖家售价是多少;
2.输出返回:
出来结果希望是同款产品的在不同地方的价格清单列表,返回一个List<String>
《Mysql》 in jd price is 88.05
《Mysql》 in Dangdang price is 86.11
《Mysql》 in Taobao price is 88.05
3.解决方案,比对同一个商品在各个平台上的价格,要求获得一个清单列表
3.1 step by step,按部就班,一个一个查
3.2 all in, 一口气多线程异步任务同时查询
实现代码:
商城对象封装,对外暴露查价方法,模拟根据产品查询价格
1 class NetMall { 2 @Getter 3 private String netMall; 4 5 public NetMall(String netMall) { 6 this.netMall = netMall; 7 } 8 9 public double calcPrice(String productName) { 10 return mockQueryPriceFromMall(productName); 11 } 12 13 private double mockQueryPriceFromMall(String productName) { 14 try { 15 TimeUnit.SECONDS.sleep(1); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } 19 return ThreadLocalRandom.current().nextDouble()*2 + productName.charAt(0); 20 } 21 }
查询价格实现类
1 public class CompletableFutrueMallDemo { 2 static List<NetMall> mallList = Arrays.asList( 3 new NetMall("jd"), 4 new NetMall("dangdang"), 5 new NetMall("taobao") 6 ); 7 8 public static List<String> getPrice(List<NetMall> mallList, String productName) { 9 return mallList.stream() 10 .map(netMall -> formatPrice(productName, netMall)) 11 .collect(Collectors.toList()); 12 } 13 14 public static List<String> getPriceByCompletableFutrue(List<NetMall> mallList, String productName) { 15 return mallList.stream() 16 .map(netMall -> 17 CompletableFuture.supplyAsync(() -> formatPrice(productName, netMall))) 18 .collect(Collectors.toList()) 19 .stream() 20 .map(CompletableFuture::join) 21 .collect(Collectors.toList()); 22 } 23 24 private static String formatPrice(String productName, NetMall netMall) { 25 return String.format("《%s》 in %s price is %.2f", productName, netMall.getNetMall(), netMall.calcPrice(productName)); 26 } 27 28 public static void main(String[] args) { 29 System.out.println("start to query price step by step"); 30 long begin = System.currentTimeMillis(); 31 List<String> result = getPrice(mallList, "mysql"); 32 long end = System.currentTimeMillis(); 33 System.out.println("cost time is " + (end - begin) + "ms"); 34 35 System.out.println("================================="); 36 37 System.out.println("start to query price step by CompletableFutrue");
38 begin = System.currentTimeMillis(); 39 result = getPriceByCompletableFutrue(mallList, "mysql"); 40 end = System.currentTimeMillis(); 41 System.out.println("cost time is " + (end - begin) + "ms"); 42 43 System.out.println("===========result show==========="); 44 for (String s : result) { 45 System.out.println(s); 46 } 47 } 48 }
标签:JUC,String,System,productName,netMall,CompletableFutrue,println,电商,out From: https://www.cnblogs.com/zhaohan258/p/18244866