CompletableFuture超时用法

/**
  * 接收到lpn:如果5s内接收到iu,那就返回lpn:iu;否则返回lpn
  * 接收到iu:如果5s内没接收到lpn,那就返回lpn:iu;否则返回iu
  *
  *
  * @author hyu
  */

 @RequestMapping("/test")
 @RestController
 public class TestController {
     private static ScheduledFuture timeOutFuture = null;
     private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     private static CompletableFuture lpnFuture ;
     private static CompletableFuture iuFuture ;
     private static CompletableFuture iuLpnFuture;

     @GetMapping("/setLpn")
     public ResponseEntity setLpn(String lpn) {
         lpnFuture = CompletableFuture.completedFuture(lpn);
         normalCheck();
         if(lpnFuture != null){
             lpnFuture.acceptEither(timeoutAfter(lpn,5,TimeUnit.SECONDS),r->{});
         }
         return new ResponseEntity<>(HttpStatus.OK);
     }

     @GetMapping("/setIu")
     public ResponseEntity setIu(String iu) {
         iuFuture = CompletableFuture.completedFuture(iu);
         normalCheck();
         if(iuFuture != null){
             iuFuture.acceptEither(timeoutAfter(iu,5,TimeUnit.SECONDS),r->{});
         }
         return new ResponseEntity<>(HttpStatus.OK);
     }

     /**
      * 正常结果返回
      */
     public void normalCheck(){
         if(iuFuture != null && lpnFuture != null){
             lpnFuture.thenCombine(iuFuture, (result1, result2) -> {
                 //result1和result2分别为cf1和cf2的结果
                 return result1 + ":" + result2;
             }).thenAccept(result3 -> {
                 // 结果处理
                 System.out.println("normal result>"+result3);
                 lpnFuture = null;
                 iuFuture = null;
                 iuLpnFuture = null;
                 // 取消定时器
                 if(timeOutFuture != null){
                     timeOutFuture.cancel(true);
                 }
             });
         }
     }

     /**
      * 超时返回结果
      * @param r
      * @param timeout
      * @param unit
      * @return
      */
     public CompletableFuture timeoutAfter(String r,long timeout, TimeUnit unit) {
         CompletableFuture result = new CompletableFuture<>();
         timeOutFuture = scheduler.schedule(()->{
             iuLpnFuture = CompletableFuture.completedFuture(r);
             iuLpnFuture.thenAccept(r1->{
                 System.out.println("timeout result>"+r1);
             });
             iuLpnFuture = null;
             lpnFuture = null;
             iuFuture = null;
         },timeout,unit);
         //scheduler.schedule(() -> result.completeExceptionally(new TimeoutException()), timeout, unit);
         return result;
     }
 }
 

                            
                        
                    
                    
                    

你可能感兴趣的:(CompletableFuture超时用法)