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

The following examples show how to use org.springframework.web.context.request.async.WebAsyncTask. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Milkomeda   Source File: CometAspect.java    License: 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 2
Source Project: Spring-5.0-Cookbook   Source File: DeptAsyncController.java    License: 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 3
Source Project: Spring-5.0-Cookbook   Source File: DataController.java    License: 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 4
Source Project: spring-cloud-sleuth   Source File: TraceWebAspect.java    License: 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 5
@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 6
@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 7
Source Project: Spring-5.0-Cookbook   Source File: DataController.java    License: 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 8
Source Project: Spring-5.0-Cookbook   Source File: ServiceController.java    License: 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 9
Source Project: Spring-5.0-Cookbook   Source File: ServiceController.java    License: 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 10
Source Project: Spring-5.0-Cookbook   Source File: DeptAsyncController.java    License: 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 11
Source Project: Spring-5.0-Cookbook   Source File: EmpAsyncController.java    License: 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 12
Source Project: Spring-5.0-Cookbook   Source File: DeptAsyncController.java    License: 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 13
Source Project: Spring-5.0-Cookbook   Source File: EmpAsyncController.java    License: 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 14
Source Project: Spring-5.0-Cookbook   Source File: DeptAsyncController.java    License: 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 15
Source Project: Spring-5.0-Cookbook   Source File: DataController.java    License: 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 16
Source Project: Spring-5.0-Cookbook   Source File: ServiceController.java    License: 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 17
Source Project: Spring-5.0-Cookbook   Source File: EmpAsyncController.java    License: 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 18
@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 19
Source Project: java-spring-cloud   Source File: TracedAsyncWebAspect.java    License: 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 20
Source Project: java-spring-cloud   Source File: WebAsyncTaskTest.java    License: 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 21
@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 22
@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 23
Source Project: spring-boot-cookbook   Source File: AsyncController.java    License: 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 24
Source Project: MultimediaDesktop   Source File: MusicController.java    License: 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 25
Source Project: MultimediaDesktop   Source File: MovieController.java    License: 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 26
@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 27
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return WebAsyncTask.class.isAssignableFrom(returnType.getParameterType());
}
 
Example 28
Source Project: Milkomeda   Source File: Pulsar.java    License: 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
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return WebAsyncTask.class.isAssignableFrom(returnType.getParameterType());
}
 
Example 30
Source Project: Spring-5.0-Cookbook   Source File: DeptFeignController.java    License: MIT License 4 votes vote down vote up
@RequestMapping(value = "/feignAsyncList", method = RequestMethod.GET, produces = "application/json")
  public WebAsyncTask<List<Department>> allAsyncDepts()			    {
WebAsyncTask<List<Department>> depts = deptListClient.getAsyncListDepts();
return depts;
    }