Async异步处理【Springboot】

简单实现异步处理

①. 先建立一个controller目录,再建一个AsynController.java

package com.gql.controller;

import com.gql.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author gql
 * @date 2021/11/26 - 23:04
 */
@RestController
public class AsyncController
{
    @Autowired
    AsyncService asyncService;
    @RequestMapping("/hello")
    public String hello(){
      asyncService.hello();
      return "ok";
    }
}

②.建立一个service目录,再建立一个AsynController.java

package com.gql.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author gql
 * @date 2021/11/26 - 23:03
 */
@Service
public class AsyncService {

    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();

        }
        System.out.println("数据加载中");
    }

}

③ 启动项目

package com.gql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
public class SpringbootAsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootAsyncApplication.class, args);
    }

}

④ 效果

1.在三秒以后我们idea的console会显示

在这里插入图片描述

2.然后页面这时候三秒后也会显示

在这里插入图片描述
但是一般这样我们前端肯定会很难受啊,要等一会(线程等待)才能显示页面
所以就压有一个方法来解决这个问题,你访问localhost:8080/hello
会直接显示前端页面,但是我们的idea显示还是会在三秒以后才出现下面的画面
在这里插入图片描述
这是怎么实现的那,其实很简单
在我们调用的方法上面加入注解@Async

   @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();

        }
        System.out.println("数据加载中");
    }

然后在我们启动的项目(主项目)里面加入@EnableAsync来开启异步注释功能

@EnableAsync
@SpringBootApplication
public class SpringbootAsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootAsyncApplication.class, args);
    }

}

这样我们就可以,先出现前端ok页面(秒刷新),三秒后再idea的console才出现数据加载中
实现起来也是相当简单

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
)">
< <上一篇
下一篇>>