Java Code Examples for org.springframework.web.context.request.async.DeferredResult#onCompletion()

The following examples show how to use org.springframework.web.context.request.async.DeferredResult#onCompletion() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MyController.java    From pragmatic-java-engineer with GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping("/async/deferred")
@ResponseBody
public DeferredResult<String> quotes() {
    DeferredResult<String> deferredResult = new DeferredResult<String>(2000L);
    deferredResult.onCompletion(new Runnable() {
        @Override
        public void run() {
            System.out.println("Deferred Result done !!!");
        }
    });

    executor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            deferredResult.setResult("Deferred Result");
        }
    });

    return deferredResult;
}
 
Example 2
Source File: DeferredResultController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping("/async-deferredresult")
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
    LOG.info("Received request");
    DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();

    deferredResult.onCompletion(() -> LOG.info("Processing complete"));

    CompletableFuture.supplyAsync(() -> {
        LOG.info("Processing in separate thread");
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "OK";
    })
        .whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));

    LOG.info("Servlet thread freed");
    return deferredResult;
}
 
Example 3
Source File: DeferredResultController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping("/async-deferredresult")
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
    LOG.info("Received request");
    DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();

    deferredResult.onCompletion(() -> LOG.info("Processing complete"));

    CompletableFuture.supplyAsync(() -> {
        LOG.info("Processing in separate thread");
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "OK";
    })
        .whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));

    LOG.info("Servlet thread freed");
    return deferredResult;
}
 
Example 4
Source File: Pulsar.java    From Milkomeda with MIT License 4 votes vote down vote up
/**
 * 对使用了 @PulsarFlow 注解实现环绕切面
 *
 * @param joinPoint 切面连接点
 * @return 响应数据对象
 * @throws Throwable 可抛出异常
 */
@Around("@annotation(com.github.yizzuide.milkomeda.pulsar.PulsarFlow)")
Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    // 检测方法返回值
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    String invokeMethodName = joinPoint.getSignature().getName();
    if (methodSignature.getReturnType() != Object.class) {
        throw new ClassCastException("You must set [Object] return type on method " +
                invokeMethodName);
    }

    // 获取注解信息
    PulsarFlow pulsarFlow = getAnnotation(joinPoint, PulsarFlow.class);

    // 如果没有设置DeferredResult,则使用WebAsyncTask
    if (!pulsarFlow.useDeferredResult()) {
        // 返回异步任务(交给统一异常处理响应)
        /*if (null != timeoutCallback) {
            webAsyncTask.onTimeout(() -> this.timeoutCallback);
        }*/
        return new WebAsyncTask<>(new WebAsyncTaskCallable(joinPoint));
    }

    // 使用DeferredResult方式
    DeferredResult<Object> deferredResult = new DeferredResult<>();

    // 设置DeferredResult的错误处理(交给统一异常处理响应)
    /*if (null != timeoutCallback) {
        // 适配超时处理
        deferredResult.onTimeout(() -> deferredResult.setResult(this.timeoutCallback.get()));
    }
    if (null != errorCallback) {
        deferredResult.onError((throwable) -> deferredResult.setErrorResult(errorCallback.apply(throwable)));
    }*/

    // 创建增强DeferredResult
    PulsarDeferredResult pulsarDeferredResult = new PulsarDeferredResult();
    pulsarDeferredResult.setDeferredResult(deferredResult);

    // 准备设置DeferredResultID
    String id = pulsarFlow.id();
    String idValue = null;
    if (!StringUtils.isEmpty(id)) {
        // 解析表达式
        idValue = extractValue(joinPoint, id);
        pulsarDeferredResult.setDeferredResultID(idValue);
        // 注解设置成功,放入容器
        putDeferredResult(pulsarDeferredResult);
    }

    // 调用方法实现
    Object returnObj = joinPoint.proceed(injectParam(joinPoint, pulsarDeferredResult, pulsarFlow,
            StringUtils.isEmpty(idValue)));

    // 方法有返回值且不是DeferredResult,则不作DeferredResult处理
    if (null != returnObj && !(returnObj instanceof DeferredResult)) {
        // 通过注解存放过,则删除
        if (null != idValue) {
            removeDeferredResult(idValue);
        }
        return returnObj;
    }

    // 检查是否设置标识
    if (null == pulsarDeferredResult.getDeferredResultID()) {
        throw new IllegalArgumentException("You must invoke setDeferredResultID method of PulsarDeferredResult parameter on method " +
                invokeMethodName);
    }

    // 如果注解没有设置,在方法设置后放入容器
    if (null == idValue) {
        putDeferredResult(pulsarDeferredResult);
    }

    // 无论超时还是成功响应,删除这个DeferredResult
    deferredResult.onCompletion(() -> removeDeferredResult(pulsarDeferredResult.getDeferredResultID()));

    // 返回
    return deferredResult;
}
 
Example 5
Source File: ConsumerGroupNotifyController.java    From pmq with Apache License 2.0 4 votes vote down vote up
@PostMapping("/getConsumerGroupPolling")
public DeferredResult<GetConsumerGroupResponse> getConsumerGroupPolling(
		@RequestBody GetConsumerGroupRequest request) {
	GetConsumerGroupResponse response = new GetConsumerGroupResponse();
	response.setSuc(true);
	response.setSleepTime(RandomUtils.nextInt(50, 2000));
	response.setBrokerMetaMode(soaConfig.getBrokerMetaMode());
	DeferredResult<GetConsumerGroupResponse> deferredResult = new DeferredResult<>(
			soaConfig.getPollingTimeOut() * 1000L, response);
	GetConsumerGroupResponse getApplicationResponse = doCheckConsumerGroupPolling(request);
	if (getApplicationResponse != null) {
		deferredResult.setResult(getApplicationResponse);
	} else {
		mapAppPolling.put(request, deferredResult);
		long count = longPollingCounter.incrementAndGet();
		TraceMessageItem traceMessageItem = new TraceMessageItem();
		traceMessageItem.status = count + "";
		if (count > soaConfig.getPollingSize()) {
			response.setSleepTime(RandomUtils.nextInt(50, 2000));
			deferredResult.setResult(response);
			longPollingCounter.decrementAndGet();
		} else {
			deferredResult.onTimeout(() -> {
				getFollowMsg(request, "getConsumerGroupPolling time out notify");
			});
			deferredResult.onCompletion(() -> {
				Transaction transaction = Tracer.newTransaction("Service", "getConsumerGroupPolling");
				try {
					if (mapAppPolling.remove(request) != null) {
						long count1 = longPollingCounter.decrementAndGet();
						traceMessageItem.msg = count + "_" + count1;
						traceMessage3.add(traceMessageItem);
					}
					transaction.setStatus(Transaction.SUCCESS);
				} catch (Exception e) {
					transaction.setStatus(e);
				} finally {
					transaction.complete();
				}
			});
		}
	}
	return deferredResult;
}
 
Example 6
Source File: ClientAppNotifyController.java    From radar with Apache License 2.0 4 votes vote down vote up
@PostMapping("/getAppPolling")
public DeferredResult<GetAppResponse> getServicePolling(@RequestBody GetAppRequest request) {
	GetAppResponse response = new GetAppResponse();
	response.setSuc(true);
	response.setSleepTime(RandomUtils.nextInt(50,2000));
	request.setInTime(System.currentTimeMillis());
	DeferredResult<GetAppResponse> deferredResult = new DeferredResult<>(TIMEOUT, response);
	GetAppResponse getApplicationResponse = doCheckServPolling(request);
	if (getApplicationResponse != null) {
		if (soaConfig.isFullLog()) {
			getFollowMsg(request, "getServicePolling direct end notify");
		}
		deferredResult.setResult(getApplicationResponse);
	} else {
		mapAppPolling.put(request, deferredResult);
		if (soaConfig.isFullLog()) {
			getFollowMsg(request, "getServicePolling wait notify");
		}
		long count = longPollingCounter.incrementAndGet();
		TraceMessageItem traceMessageItem = new TraceMessageItem();
		
		traceMessageItem.status = count + "";			
		if (count > soaConfig.getPollingSize()) {
			if (soaConfig.isFullLog()) {
				getFollowMsg(request, "getServicePolling exce size notify");
			}
			response.setSleepTime(RandomUtils.nextInt(50,2000));
			deferredResult.setResult(response);
			longPollingCounter.decrementAndGet();
			
		} else {
			deferredResult.onTimeout(() -> {
				getFollowMsg(request, "getServicePolling time out notify");
				logWatchedKeysToCat(request, "infrastructure.LongPoll.TimeOutKeys");
			});
			deferredResult.onCompletion(() -> {
				Transaction transaction = Tracer.newTransaction("Service", "getServicePolling");
				try {
					if (mapAppPolling.remove(request) != null) {
						if (soaConfig.isFullLog()) {
							getFollowMsg(request, "getServicePolling finished notify");
						}
						long count1 = longPollingCounter.decrementAndGet();							
						traceMessageItem.msg = count + "_" + count1;
						traceMessageItem.end();
						traceMessage3.add(traceMessageItem);
						logWatchedKeysToCat(request, "infrastructure.LongPoll.CompletionKeys");
					}
					transaction.setStatus(Transaction.SUCCESS);
				} catch (Exception e) {
					transaction.setStatus(e);
				} finally {
					transaction.complete();
				}
			});
		}
	}
	return deferredResult;
}