openFeign整合CompletableFuture实现微服务间异步远程调用并且接收结果
前言:关于openFeign就不废话了,本文直接记录在使用openFeign的基础上整合CompletableFuture实现微服务间异步远程调用并且接收结果,异步调用有很多实现方式,但大都只返回是否调用成功却很少有方式可以在异步调用的基础上接收到被调用方返回的结果,获取线程的三种方式中继承Thread和实现Runnable都没有返回结果,而Callable+Future可以得到返回值,因此,Future的价值可以被压榨一番,实现了Future接口的CompletableFuture也难辞其咎,下面将对CompletableFuture进行一次简单的压榨。
一、服务提供方提供个接口等着被消费
Service:
@Service public class DeviceService { public String getDevice() throws InterruptedException { System.out.println("设备服务被调用"); Thread.sleep(500);//模拟执行时间 return "这里是设备服务端!"; } }
Controller:
@Autowired private DeviceService deviceService; @RequestMapping("/d") public String deviceInfo() throws InterruptedException { String device = this.deviceService.getDevice(); return device; }
二、公共API
@FeignClient(name = "manager-device") public interface DeviceClient { @RequestMapping("/d") public String deviceInfo(); }
三、服务消费方开始远程调用
Controller:
@RequestMapping("/asycgd") public String getAsycDevice() throws ExecutionException, InterruptedException { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { //在这调用 return this.deviceClient.deviceInfo(); }); //在这接收返回值 future.handle((v,e)->{ if (e != null) { //出现异常处理 e.getMessage(); }else { //v就是远程调用返回来的东西 System.out.println(Thread.currentThread().getName()+":"+v); } return v; }); return future.get();//扔给前端 }
四、测试结果
启动压力测试工具jmeter整200个线程轮番压它
明显是异步调用的,浏览器也得到了返回值。
关于CompletableFuture类提供的一些方法详细用法如下.......我饿了去抢饭吃了,,,可以看下面这些,都介绍的很详细:
https://zhuanlan.zhihu.com/p/344431341
https://zhuanlan.zhihu.com/p/378405637
Oracle官方文档在这:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html