Java 实现异步请求方式四:线程池+DeferredResult方式

1、线程池保持队列+DeferredResult配置结果信息与委托事件

private ExecutorService threadPool = Executors.newFixedThreadPool(10);

DeferredResult

2、代码示例

package com.listen.demo.ctr;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * @author liuxd
 * @version 1.0
 * @date 2019-12-25 11:36
 */
@Controller
@RequestMapping("/api")
@Slf4j
public class IVController {

    private ExecutorService threadPool = Executors.newFixedThreadPool(10);

    @RequestMapping(value = "/req4", method = GET)
    @ResponseBody
    public DeferredResult req4() {
        log.info("主线程名称:" + Thread.currentThread().getName());

        //设置超时时间20秒
        DeferredResult deferredResult = new DeferredResult(20000L);

        deferredResult.onTimeout(new Runnable() {
            @Override
            public void run() {
                log.error("异步请求超时");
                deferredResult.setResult("异步请求超时");
            }
        });
        deferredResult.onCompletion(new Runnable() {
            @Override
            public void run() {
                log.info("异步调用结束");
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                log.info("新线程名称:" + Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (Exception e) {
                    log.error("异步线程发生异常");
                    e.printStackTrace();
                }
                deferredResult.setResult("异步请求返回信息");
            }
        });

        return deferredResult;
    }
}

 

你可能感兴趣的:(解决方案,系统架构,Java)