性能优化-技术专题-并发编程

{"type":"doc","content":[{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"系统性能优化之并发编程"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"一.什么是高并发"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 高并发(High Concurrency)是互联网分布式系统架构设计中必须考虑的因素之一。它通常是指,通过设计保证系统能够同时并行处理很多请求。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":" 高并发指标通常有四点:响应时间(RT)、吞吐量(Throughput)、QPS(Queries-per-second)、并发用户数。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":" 注:一个用户一秒内狂点按钮10次,这不是并发。只有10次请求在同一时刻同时向服务器发送请求(比如用CountDownLatch模拟实现),这才是并发。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"1.1 响应时间(RT)"}]},{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"响应时间是指系统对请求作出响应的时间,一般来讲,用户能接受的响应时间是小于5秒。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"1.2 吞吐量(Throughput)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" "},{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"吞吐量是指系统在单位时间内处理请求的数量。对于无并发的应用系统而言,吞吐量与响应时间成严格的反比关系,实际上此时吞吐量就是响应时间的倒数。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" "},{"type":"text","marks":[{"type":"strong"}],"text":"一个系统的吞度量(承压能力)与"},{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"request对CPU的消耗、外部接口、IO等等紧密关联。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"系统吞吐量几个重要参数:"},{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"QPS(TPS)、并发数、响应时间"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"QPS(TPS):每秒钟request/事务数量"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"并发数: 系统同时处理的request/事务数量"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"响应时间: 一般取平均响应时间"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"理解了上面三个要素的意义之后,就能推算出它们之间的关系:"}]},{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"QPS(TPS)= 并发数/平均响应时间"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 一个系统吞吐量通常由QPS(TPS)、并发数两个因素决定,每套系统这两个值都有一个相对极限值,在应用场景访问压力下,只要某一项达到系统最高值,系统的吞吐量就上不去了,如果压力继续增大,系统的吞吐量反而会下降,原因是系统超负荷工作,上下文切换、内存等等其它消耗导致系统性能下降。"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"1.3 QPS(Queries-per-second)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"每秒响应请求数"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"1.4 并发用户数"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"并发用户数是指系统可以同时承载的正常使用系统功能的用户的数量。与吞吐量相比,并发用户数是一个更直观但也更笼统的性能指标。实际上,并发用户数是一个非常不准确的指标,因为用户不同的使用模式会导致不同用户在单位时间发出不同数量的请求。"}]},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"二、高并发带来的问题"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"2.1 服务端"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"某一时间片刻系统流量异常高,系统濒临阀值"},{"type":"text","text":";"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"服务器CPU,内存爆满,磁盘IO繁忙"},{"type":"text","text":";"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"系统雪崩:分布式系统中经常会出现某个基础服务不可用造成整个系统不可用的情况,这种现象被称为服务雪崩效应。"},{"type":"text","text":"服务雪崩效应是一种因服务提供者的不可用导致服务调用者的不可用,并将不可用逐渐放大的过程。A为服务提供者,B为A的服务调用者,C和D是B的服务调用者。当A的不可用,引起B的不可用,并将不可用逐渐放大C和D时,服务雪崩就形成了。"}]}]}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"2.2 用户角度"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}}],"text":"使用体验差"}]},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"三、并发解决方案-四大法定"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"缓存:Redis"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"异步:消息中间件MQ"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"并发编程"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#F5222D","name":"red"}},{"type":"strong"}],"text":"分布式"}]}]}]},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"四、优化方案——并发编程"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"4.1阿里笔试题"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"支付宝登录后,请问你可以从哪些角度优化提升性能?业务场景架构图"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/c1/c100de770045e7bee4b3704c5c714f22.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"horizontalrule"},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/6b/6b0aedec07df6a644380ff51e2bf6140.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"4.2 模拟业务场景"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 采用SpringBoot创建两个项目,一个项目(remote-server)为模拟远程服务接口项目,提供用户基本信息、用户余额查询等API。另外一个项目(app-server)调用远程服务接口,然后用fastjson组装数据后向APP端提供统一的用户信息API。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"4.2.1 remote-server项目"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"1、端口设置8081"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"server:\n port: 8081\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"2、导入我们需要用到的fastjson"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":" \n com.alibaba\n fastjson\n 1.2.62\n "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"3、创建两个实体类,分别为:用户基本信息"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"public class UserBaseInfo {\n private String userId;\n private String userName;\n private String sex;\n private int age;\n // get set 省略\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用户余额"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"public class UserMoney {\n private String userId;\n private String money;\n // get set 省略\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"4、分别提供两个API供远程调用,分别为:用户基本信息API"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"@RestController\n@RequestMapping(\"users-base\")\npublic class UserBaseInfoController {\n @GetMapping(\"/{userId}\")\n public UserBaseInfo getUserBaseInfo(@PathVariable String userId){\n System.out.println(\"userId:\"+userId);\n try {\n // 模拟业务逻辑,等待2秒\n Thread.sleep(2000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n UserBaseInfo userBaseInfo = new UserBaseInfo();\n userBaseInfo.setUserId(\"1\");\n userBaseInfo.setUserName(\"AlanChen\");\n userBaseInfo.setSex(\"男\");\n userBaseInfo.setAge(18);\n return userBaseInfo;\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用户余额API"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"@RestController\n@RequestMapping(\"users-money\")\npublic class UserMoneyController {\n\n @GetMapping(\"/{userId}\")\n public UserMoney getUserMoney(@PathVariable String userId){\n System.out.println(\"userId:\"+userId);\n try {\n // 模拟业务逻辑,等待2秒\n Thread.sleep(2000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n UserMoney userMoney = new UserMoney();\n userMoney.setUserId(\"1\");\n userMoney.setMoney(\"1000\");\n return userMoney;\n }\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"5、用Postman测试接口如下"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/e1/e1191b4b52a032f57a16822e992dc503.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","text":"用户基本信息"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/96/96e120688330209d981df8cd4c2b139c.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","text":"用户余额"}]},{"type":"heading","attrs":{"align":null,"level":5},"content":[{"type":"text","text":"4.2.2 app-server项目"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"1、端口设置为8888"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"server:\n port: 8888\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"2、导入我们需要用到的fastjson"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":" \n com.alibaba\n fastjson\n 1.2.62\n \n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"3、用Spring的RestTemplate接口实现远程调用服务"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"/**\n * @author Alan Chen\n * @description 远程接口\n * @date 2020-07-20\n */\n@Service\npublic class RemoteService {\n\n /**\n * 获取用户基本信息\n * @param userId\n * @return\n */\n public String getUserInfo(String userId){\n RestTemplate restTemplate = new RestTemplate();\n long t1 = System.currentTimeMillis();\n String result = restTemplate.getForObject(\"http://127.0.0.1:8081/users-base/{userId}\",String.class,userId);\n\n System.out.println(\"获取用户基本信息时间为:\"+(System.currentTimeMillis()-t1));\n return result;\n }\n\n /**\n * 获取用户余额\n * @param userId\n * @return\n */\n public String getUserMoney(String userId){\n RestTemplate restTemplate = new RestTemplate();\n long t1 = System.currentTimeMillis();\n String result = restTemplate.getForObject(\"http://127.0.0.1:8081/users-money/{userId}\",String.class,userId);\n\n System.out.println(\"获取用户余额时间为:\"+(System.currentTimeMillis()-t1));\n return result;\n }\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"4、调用远程接口,数据组装后返回给客户端"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"@Service\npublic class UserService {\n\n @Autowired\n RemoteService remoteService;\n\n ExecutorService task = Executors.newFixedThreadPool(10);\n\n /**\n * 串行调用远程接口\n * @param userId\n * @return\n */\n public String getUserInfo(String userId){\n\n long t1 = System.currentTimeMillis();\n\n // 分别调用两个接口\n String v1 = remoteService.getUserInfo(userId);\n JSONObject userInfo = JSONObject.parseObject(v1);\n\n String v2 = remoteService.getUserMoney(userId);\n JSONObject moneyInfo = JSONObject.parseObject(v2);\n\n // 结果集进行合并\n JSONObject result = new JSONObject();\n result.putAll(userInfo);\n result.putAll(moneyInfo);\n\n System.out.println(\"执行总时间为:\"+(System.currentTimeMillis()-t1));\n\n return result.toString();\n }\n\n /**\n * 线程并行调用远程接口(Thread+FutureTask+Callable)\n * @param userId\n * @return\n */\n public String getUserInfoThread(String userId){\n // Runnable没有返回值,Callable有返回值\n\n long t1 = System.currentTimeMillis();\n\n Callable queryUserInfo = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v1 = remoteService.getUserInfo(userId);\n JSONObject userInfo = JSONObject.parseObject(v1);\n return userInfo;\n }\n };\n\n Callable queryUserMoney = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v2 = remoteService.getUserMoney(userId);\n JSONObject moneyInfo = JSONObject.parseObject(v2);\n return moneyInfo;\n }\n };\n\n FutureTask queryUserInfoFutureTask = new FutureTask<>(queryUserInfo);\n FutureTask queryUserMoneyFutureTask = new FutureTask<>(queryUserMoney);\n\n new Thread(queryUserInfoFutureTask).start();\n new Thread(queryUserMoneyFutureTask).start();\n\n // 结果集进行合并\n JSONObject result = new JSONObject();\n try {\n result.putAll(queryUserInfoFutureTask.get());// 阻塞方法拿结果\n result.putAll(queryUserMoneyFutureTask.get());// 阻塞方法拿结果\n } catch (Exception e) {\n e.printStackTrace();\n }\n System.out.println(\"执行总时间为:\"+(System.currentTimeMillis()-t1));\n return result.toString();\n }\n\n /**\n * 线程并行调用远程接口(Thread+Callable+自定义FutureTask)\n * @param userId\n * @return\n */\n public String getUserInfoThreadMyFutureTask(String userId){\n // Runnable没有返回值,Callable有返回值\n long t1 = System.currentTimeMillis();\n Callable queryUserInfo = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v1 = remoteService.getUserInfo(userId);\n JSONObject userInfo = JSONObject.parseObject(v1);\n return userInfo;\n }\n };\n Callable queryUserMoney = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v2 = remoteService.getUserMoney(userId);\n JSONObject moneyInfo = JSONObject.parseObject(v2);\n return moneyInfo;\n }\n };\n AlanChenFutureTask queryUserInfoFutureTask = new AlanChenFutureTask<>(queryUserInfo);\n AlanChenFutureTask queryUserMoneyFutureTask = new AlanChenFutureTask<>(queryUserMoney);\n new Thread(queryUserInfoFutureTask).start();\n new Thread(queryUserMoneyFutureTask).start();\n // 结果集进行合并\n JSONObject result = new JSONObject();\n try {\n result.putAll(queryUserInfoFutureTask.get());// 阻塞方法拿结果\n result.putAll(queryUserMoneyFutureTask.get());// 阻塞方法拿结果\n } catch (Exception e) {\n e.printStackTrace();\n }\n System.out.println(\"执行总时间为:\"+(System.currentTimeMillis()-t1));\n return result.toString();\n }\n\n /**\n * 线程并行调用远程接口(Thread+FutureTask+Callable+ExecutorService)\n * @param userId\n * @return\n */\n public String getUserInfoThreadPool(String userId){\n // Runnable没有返回值,Callable有返回值\n\n long t1 = System.currentTimeMillis();\n\n Callable queryUserInfo = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v1 = remoteService.getUserInfo(userId);\n JSONObject userInfo = JSONObject.parseObject(v1);\n return userInfo;\n }\n };\n\n Callable queryUserMoney = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v2 = remoteService.getUserMoney(userId);\n JSONObject moneyInfo = JSONObject.parseObject(v2);\n return moneyInfo;\n }\n };\n\n FutureTask queryUserInfoFutureTask = new FutureTask<>(queryUserInfo);\n FutureTask queryUserMoneyFutureTask = new FutureTask<>(queryUserMoney);\n\n //用线程池执行\n task.submit(queryUserInfoFutureTask);\n task.submit(queryUserMoneyFutureTask);\n\n // 结果集进行合并\n JSONObject result = new JSONObject();\n try {\n result.putAll(queryUserInfoFutureTask.get());// 阻塞方法拿结果\n result.putAll(queryUserMoneyFutureTask.get());// 阻塞方法拿结果\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n System.out.println(\"执行总时间为:\"+(System.currentTimeMillis()-t1));\n\n return result.toString();\n }\n\n /**\n * 异步请求(节省tomcat线程池线程) Callable或DeferredResult\n * @param userId\n * @return\n */\n public Callable getUserInfoAsync(@PathVariable String userId){\n long t = System.currentTimeMillis();\n System.out.println(\"主线程开始...\"+Thread.currentThread());\n\n Callable callable = new Callable() {\n @Override\n public String call() throws Exception {\n long t1 = System.currentTimeMillis();\n System.out.println(\"子线程开始...\"+Thread.currentThread());\n\n String result = getUserInfoThreadPool(userId);\n\n System.out.println(\"子线程结束...\"+Thread.currentThread()+\"---->\"+(System.currentTimeMillis()-t1));\n return result;\n }\n };\n\n System.out.println(\"主线程结束...\"+Thread.currentThread()+\"---->\"+(System.currentTimeMillis()-t));\n return callable;\n }\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"5、提供Controller接口给客户端访问"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"@RestController\n@RequestMapping(\"users\")\npublic class UserController {\n\n @Autowired\n UserService userService;\n\n @GetMapping(\"/{userId}\")\n public String getUserInfo(@PathVariable String userId){\n return userService.getUserInfo(userId);\n }\n\n @GetMapping(\"/thread/{userId}\")\n public String getUserInfoThread(@PathVariable String userId){\n return userService.getUserInfoThread(userId);\n }\n\n @GetMapping(\"/thread/pool/{userId}\")\n public String getUserInfoThreadPool(@PathVariable String userId){\n return userService.getUserInfoThreadPool(userId);\n }\n\n @GetMapping(\"/thread/my_future_task/{userId}\")\n public String getUserInfoThreadMyFutureTask(@PathVariable String userId){\n return userService.getUserInfoThreadMyFutureTask(userId);\n }\n\n @GetMapping(\"/thread/async/{userId}\")\n public Callable getUserInfoAsync(@PathVariable String userId){\n return userService.getUserInfoAsync(userId);\n }\n\n}\n\n"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"4.3 优化方案详解"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"所有的优化方案都在app-server的UserService实现类里"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"4.3.1 常规实现方式:串行调用远程接口"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":" /**\n * 串行调用远程接口\n * @param userId\n * @return\n */\n public String getUserInfo(String userId){\n\n long t1 = System.currentTimeMillis();\n\n // 分别调用两个接口\n String v1 = remoteService.getUserInfo(userId);\n JSONObject userInfo = JSONObject.parseObject(v1);\n\n String v2 = remoteService.getUserMoney(userId);\n JSONObject moneyInfo = JSONObject.parseObject(v2);\n\n // 结果集进行合并\n JSONObject result = new JSONObject();\n result.putAll(userInfo);\n result.putAll(moneyInfo);\n\n System.out.println(\"执行总时间为:\"+(System.currentTimeMillis()-t1));\n\n return result.toString();\n }\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"执行结果"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/8e/8e6d71654038d974f124eeef1dbfbf79.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"postman执行结果"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/06/0679ad052d2411a12323f20cbf2dc96a.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"控制台打印执行时间"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 我看可以看到,执行时间大约是4秒钟。这种串行调用远程接口的方式,时间执行为各远程接口调用的时间总和,接口响应慢,不可取。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"4.3.2 线程并行调用远程接口:Thread+FutureTask+Callable"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"/**\n * 线程并行调用远程接口(Thread+FutureTask+Callable)\n * @param userId\n * @return\n */\n public String getUserInfoThread(String userId){\n // Runnable没有返回值,Callable有返回值\n long t1 = System.currentTimeMillis();\n Callable queryUserInfo = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v1 = remoteService.getUserInfo(userId);\n JSONObject userInfo = JSONObject.parseObject(v1);\n return userInfo;\n }\n };\n Callable queryUserMoney = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v2 = remoteService.getUserMoney(userId);\n JSONObject moneyInfo = JSONObject.parseObject(v2);\n return moneyInfo;\n }\n };\n FutureTask queryUserInfoFutureTask = new FutureTask<>(queryUserInfo);\n FutureTask queryUserMoneyFutureTask = new FutureTask<>(queryUserMoney);\n new Thread(queryUserInfoFutureTask).start();\n new Thread(queryUserMoneyFutureTask).start();\n // 结果集进行合并\n JSONObject result = new JSONObject();\n try {\n result.putAll(queryUserInfoFutureTask.get());// 阻塞方法拿结果\n result.putAll(queryUserMoneyFutureTask.get());// 阻塞方法拿结果\n } catch (Exception e) {\n e.printStackTrace();\n }\n System.out.println(\"执行总时间为:\"+(System.currentTimeMillis()-t1));\n return result.toString();\n }\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/50/500b4dd27bd5bc0f55fb49f5e653765d.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","text":"控制台打印执行时间"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 我看可以看到,执行时间大约是2秒钟,执行时间减少了一半。利用Thread+FutureTask+Callable,可以同时发送多个远程调用请求,再用FutureTask的get()方法阻塞拿到各异步请求的结果集,再进行合并。这种方案,接口执行的总时间取决于各异步远程接口调用的最长的那个时间。"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/f8/f8c6592394785b116e35d05e12cfbcf5.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","text":"线程并行调用接口"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"4.3.3 线程并行调用远程接口:Thread+Callable+自定义FutureTask"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"FutureTask除了用JDK自带的接口外,我们自己同样也可以实现一个简单的FutureTask。"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"/**\n * @author Alan Chen\n * @description 自定义FutureTask\n * @date 2020-07-20\n */\npublic class AlanChenFutureTask implements Runnable, Future {\n\n Callable callable;\n V result;\n\n public AlanChenFutureTask(Callable callable){\n this.callable = callable;\n }\n\n @Override\n public void run() {\n try {\n result = callable.call();\n synchronized (this){\n this.notifyAll();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public V get() throws InterruptedException, ExecutionException {\n if(result!=null){\n return result;\n }\n synchronized (this){\n //阻塞等待获取返回值\n this.wait();\n }\n return result;\n }\n\n @Override\n public boolean cancel(boolean mayInterruptIfRunning) {\n return false;\n }\n\n @Override\n public boolean isCancelled() {\n return false;\n }\n\n @Override\n public boolean isDone() {\n return false;\n }\n\n @Override\n public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {\n return null;\n }\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"/**\n * 线程并行调用远程接口(Thread+Callable+自定义FutureTask)\n * @param userId\n * @return\n */\n public String getUserInfoThreadMyFutureTask(String userId){\n // Runnable没有返回值,Callable有返回值\n long t1 = System.currentTimeMillis();\n Callable queryUserInfo = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v1 = remoteService.getUserInfo(userId);\n JSONObject userInfo = JSONObject.parseObject(v1);\n return userInfo;\n }\n };\n Callable queryUserMoney = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v2 = remoteService.getUserMoney(userId);\n JSONObject moneyInfo = JSONObject.parseObject(v2);\n return moneyInfo;\n }\n };\n AlanChenFutureTask queryUserInfoFutureTask = new AlanChenFutureTask<>(queryUserInfo);\n AlanChenFutureTask queryUserMoneyFutureTask = new AlanChenFutureTask<>(queryUserMoney);\n new Thread(queryUserInfoFutureTask).start();\n new Thread(queryUserMoneyFutureTask).start();\n // 结果集进行合并\n JSONObject result = new JSONObject();\n try {\n result.putAll(queryUserInfoFutureTask.get());// 阻塞方法拿结果\n result.putAll(queryUserMoneyFutureTask.get());// 阻塞方法拿结果\n } catch (Exception e) {\n e.printStackTrace();\n }\n System.out.println(\"执行总时间为:\"+(System.currentTimeMillis()-t1));\n return result.toString();\n }\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/8f/8f143cc3f3ead94ec721887b6a9602bc.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"控制台打印执行时间"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"4.3.4 线程池并行调用远程接口:Thread+FutureTask+Callable+ExecutorService"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们可以进一步进行优化,将线程换成线程池"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"/**\n * 线程池并行调用远程接口(Thread+FutureTask+Callable+ExecutorService)\n * @param userId\n * @return\n */\n public String getUserInfoThreadPool(String userId){\n // Runnable没有返回值,Callable有返回值\n\n long t1 = System.currentTimeMillis();\n\n Callable queryUserInfo = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v1 = remoteService.getUserInfo(userId);\n JSONObject userInfo = JSONObject.parseObject(v1);\n return userInfo;\n }\n };\n\n Callable queryUserMoney = new Callable() {\n @Override\n public JSONObject call() throws Exception {\n String v2 = remoteService.getUserMoney(userId);\n JSONObject moneyInfo = JSONObject.parseObject(v2);\n return moneyInfo;\n }\n };\n\n FutureTask queryUserInfoFutureTask = new FutureTask<>(queryUserInfo);\n FutureTask queryUserMoneyFutureTask = new FutureTask<>(queryUserMoney);\n\n //用线程池执行\n task.submit(queryUserInfoFutureTask);\n task.submit(queryUserMoneyFutureTask);\n\n // 结果集进行合并\n JSONObject result = new JSONObject();\n try {\n result.putAll(queryUserInfoFutureTask.get());// 阻塞方法拿结果\n result.putAll(queryUserMoneyFutureTask.get());// 阻塞方法拿结果\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n System.out.println(\"执行总时间为:\"+(System.currentTimeMillis()-t1));\n\n return result.toString();\n }\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/7d/7d0e267cb049f812a2beb41dcf6372c4.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"控制台打印执行时间"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"4.3.5 异步请求(节省tomcat线程池线程) :Callable或DeferredResult"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 我们知道tomcat的请求连接数是有限的,如果接口响应时间过长,会占用和消耗tomcat的连接数。如果tomcat主线程接收到请求后,立即开启一个子线程异步去执行业务逻辑,然后tomcat主线程快速返回释放连接,等有结果后子线程再返回给前端客户端,这样就可以大大节省tomcat的连接数,提高tomcat连接利用率。具体实现如下:"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/81/81b4724f4f86e9ac0a8d923c94ddc2d4.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"异步请求架构图"}]},{"type":"codeblock","attrs":{"lang":null},"content":[{"type":"text","text":"/**\n * 异步请求(节省tomcat线程池线程) Callable或DeferredResult\n * @param userId\n * @return\n */\n public Callable getUserInfoAsync(@PathVariable String userId){\n long t = System.currentTimeMillis();\n System.out.println(\"主线程开始...\"+Thread.currentThread());\n Callable callable = new Callable() {\n @Override\n public String call() throws Exception {\n long t1 = System.currentTimeMillis();\n System.out.println(\"子线程开始...\"+Thread.currentThread());\n String result = getUserInfoThreadPool(userId);\n System.out.println(\"子线程结束...\"+Thread.currentThread()+\"---->\"+(System.currentTimeMillis()-t1));\n return result;\n }\n };\n System.out.println(\"主线程结束...\"+Thread.currentThread()+\"---->\"+(System.currentTimeMillis()-t));\n return callable;\n }\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/14/1471dbf21eb18dbcdbf050686bae470d.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"postman执行测试"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/d4/d4980928f339dfba8852107f0b37b4b0.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"控制台打印结果"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们从打印结果中可以看到,tomcat主线程几乎只用了0毫秒就快速返回了,等子线程取到结果后再返回给客户端,消耗时间大约为2秒。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章