如果一个请求半天没处理完,网页是卡着的,ajax也没有信息返回。
    可以把时间长的部分弄成异步的。

    1. package com.lyd.swagger.service;
    2. import org.springframework.scheduling.annotation.Async;
    3. import org.springframework.stereotype.Service;
    4. //加上Async注解后,这个方法就变成了异步方法,不阻塞主线程
    5. @Async
    6. @Service
    7. public class AsyncService {
    8. public void asyncHello() {
    9. try {
    10. Thread.sleep(3000);
    11. } catch (InterruptedException e) {
    12. e.printStackTrace();
    13. }
    14. System.out.println("处理数据中...");
    15. }
    16. }
    1. package com.lyd.swagger.controller;
    2. import com.lyd.swagger.pojo.User;
    3. import com.lyd.swagger.service.AsyncService;
    4. import io.swagger.annotations.Api;
    5. import io.swagger.annotations.ApiOperation;
    6. import io.swagger.annotations.ApiParam;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.scheduling.annotation.Async;
    9. import org.springframework.web.bind.annotation.GetMapping;
    10. import org.springframework.web.bind.annotation.PostMapping;
    11. import org.springframework.web.bind.annotation.RequestMapping;
    12. import org.springframework.web.bind.annotation.RestController;
    13. @RestController
    14. public class HelloController {
    15. @Autowired
    16. AsyncService asyncService;
    17. @GetMapping("/hello")
    18. public String hello(){
    19. asyncService.asyncHello();//开启了异步,就不阻塞主线程了
    20. return "处理成功";
    21. }
    22. }
    1. package com.lyd.swagger;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.scheduling.annotation.EnableAsync;
    5. //需要在程序入口处开启异步,才能使用异步方法
    6. @EnableAsync
    7. @SpringBootApplication
    8. public class SwaggerApplication {
    9. public static void main(String[] args) {
    10. SpringApplication.run(SwaggerApplication.class, args);
    11. }
    12. }