org.springframework.web.context.request.async.WebAsyncTask Java Examples

The following examples show how to use org.springframework.web.context.request.async.WebAsyncTask. 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: TraceWebAspect.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Around("anyControllerOrRestControllerWithPublicWebAsyncTaskMethod()")
public Object wrapWebAsyncTaskWithCorrelationId(ProceedingJoinPoint pjp)
		throws Throwable {
	final WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) pjp.proceed();
	TraceContext currentSpan = this.tracing.currentTraceContext().get();
	if (currentSpan == null) {
		return webAsyncTask;
	}
	try {
		if (log.isDebugEnabled()) {
			log.debug("Wrapping callable with span [" + currentSpan + "]");
		}
		Field callableField = WebAsyncTask.class.getDeclaredField("callable");
		callableField.setAccessible(true);
		callableField.set(webAsyncTask, new TraceCallable<>(this.tracing,
				this.spanNamer, webAsyncTask.getCallable()));
	}
	catch (NoSuchFieldException ex) {
		log.warn("Cannot wrap webAsyncTask's callable with TraceCallable", ex);
	}
	return webAsyncTask;
}
 
Example #2
Source File: CometAspect.java    From Milkomeda with MIT License 6 votes vote down vote up
@Around("comet()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    Date requestTime = new Date();
    Comet comet = ReflectUtil.getAnnotation(joinPoint, Comet.class);
    // 获取记录原型对象
    HttpServletRequest request = WebContext.getRequest();
    WebCometData cometData = WebCometData.createFormRequest(request, comet.prototype(), cometProperties.isEnableReadRequestBody());
    cometData.setApiCode(comet.apiCode());
    cometData.setDescription(StringUtils.isEmpty(comet.name()) ? comet.description() : comet.name());
    cometData.setRequestType(comet.requestType());
    return applyAround(cometData, threadLocal, joinPoint, request, requestTime, comet.name(), comet.tag(), (returnData) -> {
        if (returnData.getClass() == DeferredResult.class) {
            return "[DeferredResult]";
        }
        if (returnData.getClass() == WebAsyncTask.class) {
            return "[WebAsyncTask]";
        }
        return returnData;
    });
}
 
Example #3
Source File: DeptAsyncController.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@GetMapping(value="/webSyncDept/{id}.json", produces ="application/json", headers = {"Accept=text/xml, application/json"})
public WebAsyncTask<Department> websyncDeptList(@PathVariable("id") Integer id){
   
    Callable<Department> callable = new Callable<Department>() {
    	public Department call() throws Exception {
    		
    		 ListenableFuture<Department> listenFuture = departmentServiceImpl.findAllFirstById(id);
    		 listenFuture.addCallback(new ListenableFutureCallback<Department>(){

				@Override
				public void onSuccess(Department dept) {
					result = dept;
				}

				@Override
				public void onFailure(Throwable arg0) {
					result = new Department();
				}
    			 
    		 });
    		 return result;
          }
    };
    return new WebAsyncTask<Department>(500, callable);
}
 
Example #4
Source File: DataController.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@RequestMapping(value="/web/webasync.html")
@ResponseBody
public WebAsyncTask<String> longTimeTask(){
   
    Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            Thread.sleep(3000); 
         
            System.out.println("controller#webasync task started. Thread: " +
                       Thread.currentThread()
                             .getName());
            return "Trial";
        }
    };
    return new WebAsyncTask<String>(callable);
}
 
Example #5
Source File: DataController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@RequestMapping(value="/web/webasync.html")
public WebAsyncTask<String> longTimeTask(){
   
    Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            Thread.sleep(3000); 
            logger.info("controller#longTimeTask task started.");
            System.out.println("controller#webasync task started. Thread: " +
                       Thread.currentThread()
                             .getName());
            return "Tral";
        }
    };
    return new WebAsyncTask<String>(callable);
}
 
Example #6
Source File: DeptAsyncController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@GetMapping(value="/webSyncDeptList.json", produces ="application/json", headers = {"Accept=text/xml, application/json"})
public WebAsyncTask<List<Department>> websyncDeptList(){
   
    Callable<List<Department>> callable = new Callable<List<Department>>() {
        public List<Department> call() throws Exception {
             return departmentServiceImpl.readDepartments().get(500, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Department>>(500, callable);
}
 
Example #7
Source File: ServiceController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@RequestMapping(value="/web/employeeList.json", produces ="application/json", method = RequestMethod.GET, headers = {"Accept=text/xml, application/json"})
@ResponseBody
public WebAsyncTask<List<Employee>> jsonEmpList(){
   
    Callable<List<Employee>> callable = new Callable<List<Employee>>() {
        public List<Employee> call() throws Exception {
            Thread.sleep(3000); 
            logger.info("ServiceController#jsonEmpList task started.");
            System.out.println("jsonEmpList task executor: " + Thread.currentThread().getName());
            return employeeServiceImpl.readEmployees().get(50000, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Employee>>(5000, callable);
}
 
Example #8
Source File: EmpAsyncController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@GetMapping(value="/webSyncEmpList.json", produces ="application/json", headers = {"Accept=text/xml, application/json"})
public WebAsyncTask<List<Employee>> websyncEmpList(){
   
    Callable<List<Employee>> callable = new Callable<List<Employee>>() {
        public List<Employee> call() throws Exception {
             return employeeServiceImpl.readEmployees().get(500, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Employee>>(500, callable);
}
 
Example #9
Source File: AsyncTaskMethodReturnValueHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) returnValue;
	webAsyncTask.setBeanFactory(this.beanFactory);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(webAsyncTask, mavContainer);
}
 
Example #10
Source File: TracedAsyncWebAspect.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Around("anyControllerOrRestControllerWithPublicWebAsyncTaskMethod()")
public Object tracePublicWebAsyncTaskMethods(ProceedingJoinPoint proceedingJoinPoint)
    throws Throwable {
  final WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) proceedingJoinPoint.proceed();
  Field callableField = WebAsyncTask.class.getDeclaredField("callable");
  callableField.setAccessible(true);
  // do not create span (there is always server span) just pass it to new thread.
  callableField
      .set(webAsyncTask, new TracedCallable<>(webAsyncTask.getCallable(), tracer));
  return webAsyncTask;
}
 
Example #11
Source File: WebAsyncTaskTest.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/webAsyncTask")
public WebAsyncTask<String> webAsyncTask() {
  return new WebAsyncTask<>(() -> {
    mockTracer.buildSpan("foo").start().finish();
    return "webAsyncTask";
  });
}
 
Example #12
Source File: AsyncTaskMethodReturnValueHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) returnValue;
	webAsyncTask.setBeanFactory(this.beanFactory);
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(webAsyncTask, mavContainer);
}
 
Example #13
Source File: CallableController.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@RequestMapping("/custom-timeout-handling")
public @ResponseBody
WebAsyncTask<String> callableWithCustomTimeoutHandling() {

	Callable<String> callable = new Callable<String>() {
		@Override
		public String call() throws Exception {
			Thread.sleep(2000);
			return "Callable result";
		}
	};

	return new WebAsyncTask<String>(1000, callable);
}
 
Example #14
Source File: AsyncController.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/webAsyncTask", method = RequestMethod.GET)
public WebAsyncTask longTimeTask() {
    LOGGER.info("{} 被调用.{} ", RequestHolder.getRequestFacade().getRequestURI(), Thread.currentThread());
    Callable<String> callable = () -> {
        TimeUnit.SECONDS.sleep(3);//假设是一些长时间任务
        LOGGER.info("执行成功.{}", Thread.currentThread());
        return "执行成功";
    };

    WebAsyncTask<String> asyncTask = new WebAsyncTask<>(2000, callable);//时间 的单位是ms
    /**
     * 超时了,“执行成功”这句话还会打印?
     * 超时归超时,超时并不会打断正常执行流程,
     * 但注意,出现超时后我们给客户端返回了“超时”的结果,那接下来即便正常处理流程成功,
     * 客户端也收不到正常处理成功所产生的结果了,这带来的问题就是:客户端看到了“超时”,
     * 实际上操作到底有没有成功,客户端并不知道,
     * 但通常这也不是什么大问题,因为用户在浏览器上再刷新一下就好了
     */
    asyncTask.onTimeout(
            () -> {
              /*
               ModelAndView mav = new ModelAndView("longtimetask");
                mav.addObject("result", "执行超时");
              */
                LOGGER.info("执行超时.{}", Thread.currentThread());
                return "执行超时";
            }
    );
    /**
     * 直接返回Callable<ModelAndView>都是可以的,但我们这里包装了一层,是为了上面的“超时处理”
     * Callable的call方法并不是我们直接调用的,而是在longTimeTask返回后,
     * 由Spring MVC用一个工作线程来调用
     * 即仅仅是简单地把请求处理线程的任务转交给另一工作线程而已。
     * 其实“超时处理线程”和“回调处理线程”可能都是线程池中的某个线程
     */
    return new WebAsyncTask<>(3000, callable);//时间 的单位是ms
}
 
Example #15
Source File: MusicController.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/media/music/add", method = RequestMethod.POST)
public WebAsyncTask<Void> addMovie(Model model, MultipartFile musicFile,
		MusicDto musicDto) {

	log.info("用户[" + UserUtils.getCurrentUserId() + "]正在上传音乐"
			+ ToStringBuilder.reflectionToString(musicDto));

	return new WebAsyncTask<>(fileUploadTime, new MusicAsyncCallable(model,
			musicFile, musicDto, filePath, musicService));
}
 
Example #16
Source File: MovieController.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
/**
 * 异步处理文件上传,Servlet3规范新特性,不会消耗更多的资源
 * 
 * @param model
 * @param movieFile
 * @param movieDto
 * @param madeDate
 * @param request
 * @return
 */
@RequestMapping(value = "/media/movie/add", method = RequestMethod.POST)
public WebAsyncTask<Void> addMovie(Model model, MultipartFile movieFile,
		MovieDto movieDto,
		@DateTimeFormat(pattern = "yyyy-MM-dd") Date madeDate,
		HttpServletRequest request) {

	log.info("用户[" + UserUtils.getCurrentUserId() + "]正在上传视频[标题:"+movieDto.getTitle()+"]");

	return new WebAsyncTask<Void>(fileUploadTime, new MovieAsyncCallable(model,
			movieFile, movieDto, madeDate, movieService, filePath));
}
 
Example #17
Source File: RestTemplateTraceAspectIntegrationTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/webAsyncTaskPing", method = RequestMethod.GET,
		produces = MediaType.TEXT_PLAIN_VALUE)
public WebAsyncTask<String> webAsyncTaskPing() {
	return new WebAsyncTask<>(new Callable<String>() {
		@Override
		public String call() throws Exception {
			return callAndReturnOk();
		}
	});
}
 
Example #18
Source File: AsyncTaskMethodReturnValueHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) returnValue;
	if (this.beanFactory != null) {
		webAsyncTask.setBeanFactory(this.beanFactory);
	}
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(webAsyncTask, mavContainer);
}
 
Example #19
Source File: EmpAsyncController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@GetMapping(value="/webSyncEmpList.json", produces ="application/json", headers = {"Accept=text/xml, application/json"})
public WebAsyncTask<List<Employee>> websyncEmpList(){
   
    Callable<List<Employee>> callable = new Callable<List<Employee>>() {
        public List<Employee> call() throws Exception {
             return employeeServiceImpl.readEmployees().get(500, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Employee>>(500, callable);
}
 
Example #20
Source File: AsyncTaskMethodReturnValueHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	if (returnValue == null) {
		mavContainer.setRequestHandled(true);
		return;
	}

	WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) returnValue;
	if (this.beanFactory != null) {
		webAsyncTask.setBeanFactory(this.beanFactory);
	}
	WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(webAsyncTask, mavContainer);
}
 
Example #21
Source File: DeptAsyncController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@GetMapping(value="/webSyncDeptList.json", produces ="application/json", headers = {"Accept=text/xml, application/json"})
public WebAsyncTask<List<Department>> websyncDeptList(){
   
    Callable<List<Department>> callable = new Callable<List<Department>>() {
        public List<Department> call() throws Exception {
             return departmentServiceImpl.readDepartments().get(500, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Department>>(500, callable);
}
 
Example #22
Source File: EmpAsyncController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@GetMapping(value="/webSyncEmpList.json", produces ="application/json", headers = {"Accept=text/xml, application/json"})
public WebAsyncTask<List<Employee>> websyncEmpList(){
   
    Callable<List<Employee>> callable = new Callable<List<Employee>>() {
        public List<Employee> call() throws Exception {
             return employeeServiceImpl.readEmployees().get(500, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Employee>>(500, callable);
}
 
Example #23
Source File: DeptAsyncController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@GetMapping(value="/webSyncDeptList.json", produces ="application/json", headers = {"Accept=text/xml, application/json"})
public WebAsyncTask<List<Department>> websyncDeptList(){
   
    Callable<List<Department>> callable = new Callable<List<Department>>() {
        public List<Department> call() throws Exception {
             return departmentServiceImpl.readDepartments().get(500, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Department>>(500, callable);
}
 
Example #24
Source File: DataController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@RequestMapping(value="/web/webasync.html")
public WebAsyncTask<String> longTimeTask(){
   
    Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            Thread.sleep(3000); 
            logger.info("controller#longTimeTask task started.");
            System.out.println("controller#webasync task started. Thread: " +
                       Thread.currentThread()
                             .getName());
            return "Tral";
        }
    };
    return new WebAsyncTask<String>(callable);
}
 
Example #25
Source File: ServiceController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@RequestMapping(value="/web/employeeList.json", produces ="application/json", method = RequestMethod.GET, headers = {"Accept=text/xml, application/json"})
@ResponseBody
public WebAsyncTask<List<Employee>> jsonEmpList(){
   
    Callable<List<Employee>> callable = new Callable<List<Employee>>() {
        public List<Employee> call() throws Exception {
            Thread.sleep(3000); 
            logger.info("ServiceController#jsonEmpList task started.");
            System.out.println("jsonEmpList task executor: " + Thread.currentThread().getName());
            return employeeServiceImpl.readEmployees().get(50000, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Employee>>(5000, callable);
}
 
Example #26
Source File: ServiceController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@RequestMapping(value="/web/employeeList.json", produces ="application/json", method = RequestMethod.GET, headers = {"Accept=text/xml, application/json"})
@ResponseBody
public WebAsyncTask<List<Employee>> jsonEmpList(){
   
    Callable<List<Employee>> callable = new Callable<List<Employee>>() {
        public List<Employee> call() throws Exception {
            Thread.sleep(3000); 
         
            System.out.println("jsonEmpList task executor: " + Thread.currentThread().getName());
            return employeeServiceImpl.readEmployees().get(5000, TimeUnit.MILLISECONDS);
        }
    };
    return new WebAsyncTask<List<Employee>>(5000, callable);
}
 
Example #27
Source File: AsyncTaskMethodReturnValueHandler.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return WebAsyncTask.class.isAssignableFrom(returnType.getParameterType());
}
 
Example #28
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 #29
Source File: AsyncTaskMethodReturnValueHandler.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return WebAsyncTask.class.isAssignableFrom(returnType.getParameterType());
}
 
Example #30
Source File: AsyncTaskMethodReturnValueHandler.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) {
	return (returnValue != null && returnValue instanceof WebAsyncTask);
}