Asynchronous processing of HTTP request by Java_ Method 2: through deferredresult


Spring supports HTTP asynchronous return

2. Asynchronous processing

Start a new thread, process the data and return the value.

3. Code examples


package com.liuxd.controller;

import com.liuxd.entity.Responses;
import com.liuxd.service.TaskService2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

public class AsyncCtr2 {

    private TaskService2 taskService2;

    @GetMapping(value = "/getResult")
    public DeferredResult<Responses<String>> getResult() {"HTTP request received...");
        long startTime = System.currentTimeMillis();

        DeferredResult<Responses<String>> deferredResult = new DeferredResult<Responses<String>>();

        new Thread(new Runnable() {
            public void run() {
        }).start();"The task of the receiving HTTP request thread has been completed, exit!");
        long endTime = System.currentTimeMillis();"http Total request time. " + (endTime - startTime) + "ms");

        return deferredResult;



package com.liuxd.service;

import com.liuxd.entity.Responses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;

public class TaskService2 {

    public void getData(DeferredResult<Responses<String>> deferredResult) {"Call service asynchronous with return method, start execution...");
        long startTime = System.currentTimeMillis();

        try {
        } catch (InterruptedException e) {
        }"Call service asynchronous has return method, the end of execution!!!") ;

        long endTime = System.currentTimeMillis();"Total time taken to call service asynchronous return method. " + (endTime - startTime) + "ms");

        deferredResult.setResult(new Responses<>(0, "Done", "SUCCESS"));




package com.liuxd.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

public class Responses<T> {

    private Integer code;

    private String msg;

    private T data;


4) Print results

5) Result analysis

1) The HTTP main thread accepts the request and ends after processing the request

2) After the asynchronous thread ends, returns the

Read More: