Spring Boot 基于DeferredResult的异步服务

  1. 在pom.xml中引入配置
        
            org.springframework.boot
            spring-boot-starter-web
        
  1. 建立Service层接口
public interface PiceaService {
    //无返回参数方法
    void task() throws Exception;
    //有返回参数方法
    String task2() throws Exception;
}
  1. 建立Service层实现
    Service层接口与实现,跟其他正常同步请求一样,没有差别。
@Service
public class PiceaServiceImpl implements PiceaService {

    @Override
    public void task() throws Exception {
        System.out.println("------------------------在看貂蝉,不要打扰--------------");
        Thread.sleep(1000);
    }

    @Override
    public String task2 () throws Exception {
        int k = 1;
        System.out.println("------------------------在看鱼,不要打扰--------------");
        Thread.sleep(1000);
        return (String.valueOf(k));
    }
}
  1. 建立Contoller层方法
    这是重点和核心,首先要定义一个线程池来处理异步的任务。然后就是编写异步的调用方法。
@RestController
public class PiceaServletContoller {

    @Autowired
    private PiceaService piceaService;

    @RequestMapping("/deferredresult")
    public DeferredResult deferredResult() throws Exception {
        System.out.println("控制层执行线程:" + Thread.currentThread().getName());
        //超时
        DeferredResult deferredResult = new DeferredResult(10*1000L);
        deferredResult.onTimeout(new Runnable() {
            @Override
            public void run() {
                System.out.println("异步线程执行超时");
                deferredResult.setResult("线程执行超时");
            }
        });
        deferredResult.onCompletion(new Runnable() {
            @Override
            public void run() {
                System.out.println("异步执行完毕");
            }
        });
        FIXED_THREAD_POOL.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("异步执行线程:" + Thread.currentThread().getName());
                try {
                    String str = piceaService.task2();
                    Thread.sleep(1000);
                    deferredResult.setResult("这是【异步】的请求返回: " + str);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return deferredResult;
    }

    /**
     * 线程池
     */
    public static ExecutorService FIXED_THREAD_POOL = Executors.newFixedThreadPool(10);
}
  1. 测试结果及方法
    浏览器中访问http://localhost:2001/deferredresult测试结果。

    Spring Boot 基于DeferredResult的异步服务_第1张图片

     

你可能感兴趣的:(SpringBoot-异步)