如果一个请求半天没处理完,网页是卡着的,ajax也没有信息返回。
可以把时间长的部分弄成异步的。
package com.lyd.swagger.service;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;//加上Async注解后,这个方法就变成了异步方法,不阻塞主线程@Async@Servicepublic class AsyncService {public void asyncHello() {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("处理数据中...");}}
package com.lyd.swagger.controller;import com.lyd.swagger.pojo.User;import com.lyd.swagger.service.AsyncService;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import io.swagger.annotations.ApiParam;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.annotation.Async;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloController {@AutowiredAsyncService asyncService;@GetMapping("/hello")public String hello(){asyncService.asyncHello();//开启了异步,就不阻塞主线程了return "处理成功";}}
package com.lyd.swagger;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableAsync;//需要在程序入口处开启异步,才能使用异步方法@EnableAsync@SpringBootApplicationpublic class SwaggerApplication {public static void main(String[] args) {SpringApplication.run(SwaggerApplication.class, args);}}
